问题
the demo is very simple
// 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];
and then implement the method:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
NSLog(@"---- text changed");
}
at the dealloc method :
- (void)dealloc {
[_textField removeObserver:self forKeyPath:@"text"];
}
but when i input text , the method observeValueForKeyPath:ofObject:change:context: do not execute
i don't know why
回答1:
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];
来源:https://stackoverflow.com/questions/35858831/how-to-use-kvo-to-observer-textfileds-text-change