0

I have a textfield population phone number. When i am entering phone number i am checking validation for a invalid phone number. i am using delegate method "textfield should change characters".It is working fine but it is not working for the first letter entered by the user.

extension phoneCell: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        validateInput(of: textField)
        return true
    }

Can any one help me to resolve this?

Tapan Raut
  • 850
  • 6
  • 17

2 Answers2

1

If you noticed then shouldChangeCharactersIn has a return type Bool. What it means is that when a user presses a key on the keyboard, you'll get a callback by this delegate before even registering that character in the textfield. Now if you return true, that pressed character will be reflected in the textfield if you return false, input will be discarded.

So for first time your string.count will be 1 but your textfeild.text.count will be 0.

Looking at your validation code I will suggest you add an IBAction on your textfeild for editing changed[here].

Abhishek Maurya
  • 697
  • 7
  • 19
0

What does your validation function do? Why are you returning true by default? shouldChangeCharactersIn should return the result of your validation function.