[Solved] Dismiss keyboard after a user entered 11 digit [duplicate]


This is how it works

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

   // YOU SHOULD FIRST CHECK FOR THE BACKSPACE. IF BACKSPACE IS PRESSED ALLOW IT

    if string == "" {
        return true
    }

    if let characterCount = textField.text?.count {
        // CHECK FOR CHARACTER COUNT IN TEXT FIELD
        if characterCount >= 11 {
            // RESIGN FIRST RERSPONDER TO HIDE KEYBOARD
            return textField.resignFirstResponder()
        }
    }
    return true
}

EDIT

1) You should set the IBOutlet to your textField

2) Set delegate to self, on your textField.

3) YourViewController: UIViewController, UITextFieldDelegate { }

4) Implement the delegate method as in above. check for the backspace and allow if user enters backspace to remove characters from textField.

8

solved Dismiss keyboard after a user entered 11 digit [duplicate]