1

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

kevn liu
  • 33
  • 1
  • 7

1 Answers1

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];
Matthew S.
  • 711
  • 1
  • 5
  • 22
  • thank you , i just want to use kvo to implement , but UIKit isn't KVO compliant in general – kevn liu Mar 08 '16 at 04:38
  • @kevnliu Yeah, you should have a look at http://stackoverflow.com/a/6352525/1814918 – Matthew S. Mar 08 '16 at 04:42
  • You can't addTarget:action:forControlEvents on a UITextView, its not a UIControl. You can however add new String property to a subclassed UITextView, which you update from the UITextViewTextDidChangeNotification. Then KVO works on that new property. – simplatek Oct 28 '16 at 23:06
  • @simplatek the question is about `UITextField`, not `UITextView` but the main problem is this way even won't work properly - it doesn't catch text changes if text is changed programmatically (without of cursor in text field) – Vyachaslav Gerchicov Feb 08 '19 at 12:08