How can I get a textDidChange (like for a UISearchBar) method for a UITextField?

后端 未结 7 816
不知归路
不知归路 2020-12-17 15:23

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!

7条回答
  •  醉话见心
    2020-12-17 16:04

    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

提交回复
热议问题