当我逐个删除UITextField
字段中的字符时,会调用委托方法textField:shouldChangeCharactersInRange:replacementString:
。
当我在文本字段中输入整行字符,然后按住删除键时,iOS会首先为删除的每个字符调用委托。但在某些时候(大约一半的路线)它只会删除剩下的一切。奇怪的是,发生这种情况时不会调用textField:shouldChangeCharactersInRange:replacementString:
。两者都不是textFieldShouldClear:
。
如何检测此事件?我想在textfield为空时更新UI。如果我以这种方式清空它,我的代码无法检测到。
答案 0 :(得分:0)
您可以在文本字段中注册一个对象以观察 UITextFieldDidChangeNotification 。
例如:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:self.textField];
}
然后
- (void)textFieldDidChange:(NSNotification *)notification
{
UITextField *aTextField = [notification object];
if ([aTextField.text length] == 0) {
aTextField.backgroundColor = [UIColor redColor];
}
}
如果在
上设置断点aTextField.backgroundColor = [UIColor redColor];
您将看到在最后一次删除之前调用它,将文本字段的text属性设置为nil。
你也可以简单地访问你的属性self.textField,但我正在演示如何访问通知引用的对象。如果省略-addObserver中的最后一个参数(object :):selector:name:object:它将调用该对象实例中所有textFields的通知。