1.观察属性
[self.button addObserver:self forKeyPath:@"selected" options:NSKeyValueObservingOptionNew context:nil];
2.实现方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([object isEqual:self.button] && [keyPath isEqualToString:@"selected"]) {
BOOL newValue = [[change objectForKey:@"new"] boolValue];
if (newValue) {
[self.button setTitle:@"选中" forState:UIControlStateNormal];
} else {
[self.button setTitle:@"未选中" forState:UIControlStateNormal];
}
}
}
3.移除观察者
[self.button removeObserver:self forKeyPath:@"selected"];