iOS 監聽控件某個屬性的改變observeValueForKeyPath


 

創建一個測試的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博客園看到本文,請點擊查看原文.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM