how to use kvo to observer textfiled's text ch

2019-09-11 10:41发布

This question already has an answer here:

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条回答
迷人小祖宗
2楼-- · 2019-09-11 11:36

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];
查看更多
登录 后发表回答