tags:

views:

141

answers:

1

Hello,

I would like to perform a certain action when UITextField becomes empty (user deletes everything one sign after another or uses the clear option).

I thought about using two methods

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

and

- (BOOL)textFieldShouldClear:(UITextField *)textField;

from

UITextFieldDelegate

I'm not sure how to detect the situation when the text field becomes empty? I tried with:

if ([textField.text length] == 0)

but it does't work as the fisrt of the above methods is called before the sign is deleted from the text field.

Any ideas?

+4  A: 
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSRange textFieldRange = NSMakeRange(0, [textField.text length]);
    if (NSEqualRanges(range, textFieldRange) && [string length] == 0) {
        // Game on: when you return YES from this, your field will be empty
    }
    return YES;
}

It's useful to note that the field won't be empty until after this method returns, so you might want to set some intermediate state here, then use textFieldDidEndEditing: to know that the user is done emptying out the field.

WineSoaked