1、添加观察者 (forKeyPath 表示button所要观察的属性)
[self.button addObserver:selfforKeyPath:@"titleLabel.text"options:NSKeyValueObservingOptionOld context:nil];
2、系统方法 //响应方法 (返回的object为被观察的本身(button),而不是观察的属性)
-
(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@"titleLabel.text"]) { //如果有几个监听,需要先判断监听的对象if ([change[@"old"] isEqualToString:@"点击输入"]) {
[self.button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
}else{
[self.button setTitleColor:[UIColorblackColor] forState:UIControlStateNormal];
}
}
}
3、移除观察者
- (void)dealloc
{
[self.button removeObserver:selfforKeyPath:@"titleLabel.text"];
}
1、添加观察者 (forKeyPath 表示button所要观察的属性)
[self.button addObserver:selfforKeyPath:@"titleLabel.text"options:NSKeyValueObservingOptionOld context:nil];
2、系统方法 //响应方法 (返回的object为被观察的本身(button),而不是观察的属性)
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@"titleLabel.text"]) { //如果有几个监听,需要先判断监听的对象
if ([change[@"old"] isEqualToString:@"点击输入"]) {
[self.button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
}else{
[self.button setTitleColor:[UIColorblackColor] forState:UIControlStateNormal];
}
}
}
3、移除观察者
- (void)dealloc
{
[self.button removeObserver:selfforKeyPath:@"titleLabel.text"];
}```