Detecting a change to text in UITextfield

2019-03-23 08:02发布

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条回答
在下西门庆
2楼-- · 2019-03-23 08:46

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];
查看更多
登录 后发表回答