演示非常简单
// 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 方法:
- (void)dealloc {
[_textField removeObserver:self forKeyPath:@"text"];
}
但是当我输入文本时,该方法观察到ValueForKeyPath:ofObject:change:context:不执行
我不知道为什么
你
只需要为UIControlEventEditingChanged
事件添加一个目标到UITextView
。请参阅以下示例:
[textField addTarget:self
action:@selector(textFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];