如何使用kvo观察文本文本的文本更改?

时间:2016-03-08 04:14:52

标签: ios objective-c key-value-observing

演示非常简单

// 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

我不知道为什么

1 个答案:

答案 0 :(得分:0)

您只需要将UIControlEventEditingChanged事件的目标添加到UITextView。请参阅以下示例:

[textField addTarget:self 
              action:@selector(textFieldDidChange:) 
    forControlEvents:UIControlEventEditingChanged];