Detecting a change to text in UITextfield

前端 未结 7 2023
轮回少年
轮回少年 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:49

    You could create a variable to store the original string, then register with the notification center to receive UITextFieldTextDidChangeNotification event:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateButton:) name:UITextFieldTextDidChangeNotification object:nil];
    

    Then, create a method to receive the notification, and compare the current value of the text field with the original value

    -(void) updateButton:(NSNotification *)notification {
           self.myButton.enabled = ![self.myTextField.text isEqualToString:originalString];
    }
    

    Don't forget to de-register the notification when the view controller is deallocated.

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
    

提交回复
热议问题