I have a UITextField validate that converts a user's numeric input. For example, if the user types in a 1, it becomes 0.01. If the user types 12, it becomes 0.12.
My code is working correctly when I have the validation code in textFieldDidEndEditing
. However, I've been asked to rewrite the code a bit so that the validation occurs as the user is typing as opposed to when they're finished with the textfield, so it makes sense to use shouldChangeCharactersInRange
. However, I'm a little confused how to write my code now.
Old code (working):
func textFieldDidEndEditing(_ textField: UITextField) {
if var text = textField.text,
let float = Float(text) {
let formattedFloat = float/100
if let formatterExists = formatter {
text = String.localizedStringWithFormat("\(String(describing: formatterExists))", formattedFloat)
}
let numericString = text.replacingOccurrences(of: ",", with: "")
cellModel.stringInput = numericString
}
}
New code (not working):
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let float = Float(string) {
let formattedFloat = float/100
var text = string
if let formatterExists = formatter {
text = String.localizedStringWithFormat("\(String(describing: formatterExists))", formattedFloat)
}
let numericString = text.replacingOccurrences(of: ",", with: "")
print(numericString)
textField.text = text
cellModel.stringInput = numericString
}
return false
}
I know that in my shouldChangeCharactersInRange
code, everytime I type a character, it is taking that character and applying the validation, and only doing it for a single character (as in if I type 1, I get a 0.01, and if I type a 2, the previous character gets replaced and I get a 0.02).
I'm wondering what is a good method for a user to be able to continuously input a number and keep having the validation applied as the user types.
Thanks!