检测UITextfield中的文本更改 [英] Detecting a change to text in UITextfield
问题描述
我希望能够检测到某些文本是否在 UITextField
中更改,以便我可以启用 UIButton
保存更改。
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.
推荐答案
利用UITextFieldTextDidChange通知或在文本字段上设置委托并注意textField:shouldChangeCharactersInRange:replacementString。
Take advantage of the UITextFieldTextDidChange notification or set a delegate on the text field and watch for textField:shouldChangeCharactersInRange:replacementString.
如果你想通过通知观察变化,你需要在你的代码中注册这样的通知:
If you want to watch for changes with a notification, you'll need something like this in your code to register for the notification:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:theTextField];
此处theTextField是您要观看的UITextField实例。其中self是上面代码中的实例的类必须实现textFieldDidChange,如下所示:
Here theTextField is the instance of UITextField that you want to watch. The class of which self is an instance in the code above must then implement textFieldDidChange, like so:
- (void)textFieldDidChange:(NSNotification *)notification {
// Do whatever you like to respond to text changes here.
}
如果文本字段比观察者寿命长,那么你必须取消注册以获取观察者的dealloc方法中的通知。实际上即使文本字段没有超过观察者,这也是一个好主意。
If the text field is going to outlive the observer, then you must deregister for notifications in the observer's dealloc method. Actually it's a good idea to do this even if the text field does not outlive the observer.
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
// Other dealloc work
}
这篇关于检测UITextfield中的文本更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!