I am using an altered method to this where I want to format a UITextField
as the user is typing in the number. As in I want the number being live-formatted. I am looking to change 1000 to 1,000, 50000 to 50,000 and so on.
My issue is that my UITextField
values are not updating as expected. For instance, when I type in 50000 in the UITextField
the result is coming back as 5,0000 instead of 50,000. Here is my code:
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
}
Rule number 1 of shouldChangeCharactersIn
- If you assign a value to the text field's text
property you must return false
. Returning true
tells the text field to make the original change to the text that you have already modified. That is not what you want.
You have one other major flaw in your code. It won't work in locales that use other ways to format larger numbers. Not all locales use a comma as the group separator.