1

I have a UITextField, which uses a number pad to take input. How can I dismiss it/run a method call when two digits have been entered into the textField?

Regan
  • 1,487
  • 2
  • 28
  • 43
  • 2
    Are you really sure you want to do this? The user may enter a wrong digit by mistake, and the automatic focus change could be quite frustrating. – ySgPjx Nov 20 '11 at 18:28

3 Answers3

1
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

   int count = [textField.text length];
    if(count>=2){

    [textField resignFirstResponder];
    }
return YES;
}
user9930
  • 147
  • 3
0
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let maxLength = 6
    let currentText = textField.text ?? ""
    guard let range = Range(range, in: currentText) else { return false }
    let newText = currentText.replacingCharacters(in: range, with: string)

    if newText.count == maxLength {
      view.endEditing(true)
    }

    return newText.count <= maxLength
}

Arif Fikri Abas
  • 836
  • 5
  • 9
0

Use the text field delegate method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

Here you can determine the proposed change to the text field - if the change is that the second character should be added, you can resign first responder. You should also return YES or directly set the text field's value so that the second character is updated.

Good point in the comments though - this might not be the best user experience!

jrturton
  • 118,105
  • 32
  • 252
  • 268