0

thisに変更されたメソッドを使用しています。ユーザーが数字を入力するときにUITextFieldと書式を設定します。私はライブフォーマットされている番号でしたい。私は1000から1000、50000から50,000などを変更しようとしています。UITextFieldでユーザータイプとして数値をカンマで区切る

私の問題は、私のUITextField値が期待通りに更新されないということです。たとえば、UITextFieldに50000を入力すると、結果は50,000ではなく5,0000に戻ります。ここに私のコードは次のとおりです。shouldChangeCharactersIn

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 

    //check if any numbers in the textField exist before editing 
    guard let textFieldHasText = (textField.text), !textFieldHasText.isEmpty else { 
     //early escape if nil 
     return true 
    } 

    let formatter = NumberFormatter() 
    formatter.numberStyle = NumberFormatter.Style.decimal 

    //remove any existing commas 
    let textRemovedCommma = textFieldHasText.replacingOccurrences(of: ",", with: "") 

    //update the textField with commas 
    let formattedNum = formatter.string(from: NSNumber(value: Int(textRemovedCommma)!)) 
    textField.text = formattedNum 
    return true 
} 
+0

http://stackoverflow.com/questions/24115141/swift-converting-string-to-int/34294660?s=1|0.1034#34294660 –

答えて

2

ルール番号1 - テキストフィールドのtextプロパティに値を割り当てる場合は、falseを返す必要があります。 trueを返すと、テキストフィールドに、すでに変更したテキストに元の変更を加えるように指示されます。それはあなたが望むものではありません。

コードに他に大きな欠陥が1つあります。大きな数字を書式設定するために他の方法を使用するロケールでは機能しません。すべてのロケールがグループセパレータとしてカンマを使用するわけではありません。

+0

おかげで - 私は真を使用していたことに気づきませんでした/ falseが誤って返されます。そしてロケールの問題をキャッチしてくれてありがとう。私はこれを修正しようとし、私は報告するでしょう! – Sami

1

NSNumberFormatterを使用してください。

var currencyFormatter = NumberFormatter() 
currencyFormatter.usesGroupingSeparator = true 
currencyFormatter.numberStyle = .currency 
// localize to your grouping and decimal separator 
currencyFormatter.locale = NSLocale.current 
var priceString = currencyFormatter.string(from: 9999.99) 

それはあなたがまた、あなたの必要性につきとしてロケールを設定することができ、 "$ 9,999.99"

= のような値を出力します。

0
let formatter = NumberFormatter() 
formatter.numberStyle = NumberFormatter.Style.decimal 
let textRemovedCommma = textField.text?.replacingOccurrences(of: ",", with: "") 
let formattedNum = formatter.string(from: NSNumber(value: Int(textRemovedCommma!)!)) 
textField.text = formattedNum 
+0

ねえ、そこに!このコードスニペットが解決策になるかもしれませんが、[説明を含む](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)本当にあなたの投稿の質を向上させるのに役立ちます。将来読者の質問に答えていることを覚えておいてください。そうした人々はあなたのコード提案の理由を知らないかもしれません。 – wing

関連する問題