本文介绍了如何使用kvo来观察文本文件的文本更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
演示非常简单
// add a textField to viewController's view
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 30, 375, 40)];
self.textField = textField;
textField.placeholder = @"Please input text";
// add observer for textField's attribute "text"
[textField addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
[self.view addSubview:textField];
然后实现该方法:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
NSLog(@"---- text changed");
}
在dealloc方法中:
at the dealloc method :
- (void)dealloc {
[_textField removeObserver:self forKeyPath:@"text"];
}
但是当我输入text时,方法watchValueForKeyPath:ofObject:change:context:不执行
but when i input text , the method observeValueForKeyPath:ofObject:change:context: do not execute
我不知道为什么
推荐答案
您只需要为UITextView
事件中的UIControlEventEditingChanged
事件向自己添加目标.请参见下面的示例:
You just need to add a target to self for the UIControlEventEditingChanged
event to the UITextView
. See the example below:
[textField addTarget:self
action:@selector(textFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];
这篇关于如何使用kvo来观察文本文件的文本更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!