How can I get a textDidChange method for a UITextField? I need to call a method every time a change is made to a text field. Is this possible? Thanks!
Elaborating further on Ben Gottlieb's answer above, using textField shouldChangeCharactersInRange is great but has the disadvantage that some things can happen with a one character delay.
Eg calling the below to alert you when there is no text actually is called the character after, once you have enter a character and it is no longer empty.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (!textField.text.length) {
// Do something with empty textfield
}
return YES;
}
The below method allows you to get a rudimentary change happening in your textField. Although not quite as direct as an NSNotification it still allows you to use similar methods with different textFields and so is a pretty useful thing to use when trying to get specific character changes in your textfield.
The below code fixes the character delay
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// This means it updates the name immediately
NSString * newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
textField.placeholder = newString.length ? @"" : @"Name";
return YES;
}
For this code is used to add a placeholder to a UITextField when there is no text in the textField