Search code examples
iosobjective-cuitextfielduitextfielddelegate

Trigger textFieldShouldClear programmatically


If I understand correctly, the UITextFieldDelegate method textFieldShouldClear gets triggered once the user taps on the clear button/icon provided with and enabled for a UITextField. But I need to clear the UITextField programmatically, which, in the absence of a clear method for UITextField (that I could find), I am doing like so:

textField.text = @"";

The above, however, does not trigger the textFieldShouldClear delegate method that I need. Any ideas how I could do it?

Alternatively, does my call above trigger any other delegate method? I checked, and textInputChanged is not called in this case.


Solution

  • I ended up subclassing UITextField and implementing the following method:

    - (void)setText:(NSString *)text {
    
        [super setText:text];
    
        [self textInputChanged:nil];
    }
    

    Where textInputChanged: is the UITextFieldDelegate method that I needed to get called whenever text is set programmatically.