I'm assuming that your main challenge here isn't simply checking whether the text
property of a UITextField
is empty, but getting it to perform that check as the user types. To simply check whether the text field is empty, you'd just do:
if (aTextField.text == nil || [aTextField.text length] == 0)
However, if you're trying to get the text field to "automatically" perform the calculation whenever it becomes empty, do the following: Set a delegate for the UITextField
. The delegate's textField:shouldChangeCharactersInRange:replacementString:
method is called before any characters are changed in the text field. In that method, do something like:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
[self performSelector:@selector(updateEmptyTextField:) withObject:textField afterDelay:0];
return YES;
}
You perform updateEmptyTextField
after a delay because the UITextField
hasn't yet applied the change that its delegate just approved. Then, in updateEmptyTextField:
do something like this:
- (void)updateEmptyTextField:(UITextField *)aTextField {
if (aTextField.text == nil || [aTextField.text length] == 0) {
// Replace empty text in aTextField
}
}
Note: You might need to manually run the check once when your view is first displayed, because textField:shouldChangeCharactersInRange:replacementString:
won't get called until the user starts typing in the text field.