how to use kvo to observer textfiled's text change? [duplicate]

▼魔方 西西 提交于 2019-12-12 03:54:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!