Detecting a change to text in UITextfield

RGriffiths picture RGriffiths · Mar 19, 2013 · Viewed 35.5k times · Source

I would like to be able to detect if some text is changed in a UITextField so that I can then enable a UIButton to save the changes.

Answer

DarkDust picture DarkDust · Jul 17, 2014

Instead of observing notifications or implementing textField:shouldChangeCharacterInRange:replacementString:, it's easier to just add an event target:

[textField addTarget:self
              action:@selector(myTextFieldDidChange:)
    forControlEvents:UIControlEventEditingChanged];

- (void)myTextFieldDidChange:(id)sender {
    // Handle change.
}

Note that the event is UIControlEventEditingChanged and not UIControlEventValueChanged!

The advantages over the other two suggested solutions are:

  • You don't need to remember to unregister your controller with the NSNotificationCenter.
  • The event handler is called after the change has been made which means textField.text contains the text the user actually entered. The textField:shouldChangeCharacterInRange:replacementString: delegate method is called before the changes have been applied, so textField.text does not yet give you the text the user just entered – you'd have to apply the change yourself first.