场景:使用kvo实现Label内容的监听,如果UILabel内容发生变化,则触发相应事件(这里实现另一个label内容的跟随变化)
1、注册两个观察者,分别监听callDialpadNumber和calltime这两个UILabel的text属性:
[self.callDialpadNumber addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
[self.calltime addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
2、实现回调,当key路径对应的属性(.text)发生变化时调用此方法:
// 另外两个label:inputLabel和calltimeLabel实现跟随变化
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
inputLabel.text = self.callDialpadNumber.text;
calltimeLabel.text = self.calltime.text;
}
3、最后记得移除观察者,这里在viewController的dealloc方法中进行:
- (void) dealloc{
[self.callDialpadNumber removeObserver:self forKeyPath:@"text"];
[self.calltime removeObserver:self forKeyPath:@"text”];
}