iOS 監聽控制項某個屬性的改變observeValueForKeyPath,valueforkeypath
建立一個測試的UIButton
#import "ViewController.h"@interface ViewController ()@property(nonatomic, strong)UIButton *button;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; self.button = [[UIButton alloc] initWithFrame:CGRectMake(30, 50, 50, 30)]; [self.button setTitle:@"測試" forState:UIControlStateNormal]; [self.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; self.button.layer.borderWidth = 1.0f; [self.view addSubview:self.button]; //註冊監聽button的enabled狀態 [self.button addObserver:self forKeyPath:@"enabled" options:NSKeyValueObservingOptionNew context:@"test_button"]; // 3秒鐘後改變當前button的enabled狀態 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ self.button.enabled = YES; });}
添加監聽觀察者
/** * 監聽按鈕狀態改變的方法 * * @param keyPath 按鈕改變的屬性 * @param object 按鈕 * @param change 改變後的資料 * @param context 註冊監聽時context傳遞過來的值 */-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { UIButton *button = (UIButton *)object; if (self.button == button && [@"enabled" isEqualToString:keyPath]) { NSLog(@"self.button的enabled屬性改變了%@",[change objectForKey:@"new"]); }}
log輸出
2015-06-30 11:48:32.001 監聽控制項某個屬性的改變[34212:570638] self.button的enabled屬性改變了1
如果你不是在wb145230部落格園看到本文,請點擊查看原文.