演示非常简单
// 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"];
}
但是当我输入文本时,方法observeValueForKeyPath:ofObject:change:context:do not execution
我不知道为什么
答案 0 :(得分:0)
您只需要将UIControlEventEditingChanged
事件的目标添加到UITextView
。请参阅以下示例:
[textField addTarget:self
action:@selector(textFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];