1

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!

May Yang
  • 523
  • 1
  • 5
  • 18
  • 1
    have you tried with `textFieldDidChanged` type of method. its not a delegate methods, so you have to implement it and set it with `editingChange` event of the textField. Should change method called before it change into new values. as name suggest it is "shouldChange" not "didChange". – RJE Jul 04 '17 at 01:59
  • 1
    https://stackoverflow.com/a/29783546/2303865 – Leo Dabus Jul 04 '17 at 02:08

0 Answers0