Detecting a change to text in UITextfield

前端 未结 7 1988
轮回少年
轮回少年 2021-02-07 02:15

I would like to be able to detect if some text is changed in a UITextField so that I can then enable a UIButton to save the changes.

7条回答
  •  囚心锁ツ
    2021-02-07 02:47

    For that, first you need to have your textfield have it delegate reference assigned. And the delgate, should preferably be, the vew controller which is the files owner of the view. Which goes like

    myTextField.delegate = myViewControllerReferenceVariable
    

    And in your viewController interface, tell you will be implementing UITextFieldDelegate by

    @interface MyViewController:UIViewController
    

    And in your view controller implementation override

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

    So the code will look like

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
         {
            text = [textfield.text stringByReplacingCharactersInRange:range withString:string];
            if (textfield == refToTextFieldYouWantToCheck) {
                if ( ! [textToCheck isEqualToString:text] ) {
                   [theButtonRef setEnabled:YES];
                } 
             }
               return YES; //If you don't your textfield won't get any text in it
          }
    

    You can also subscribe to notification which is sort of messy IMHO You can find how to do it here.

提交回复
热议问题