iOS 監聽控制項某個屬性的改變observeValueForKeyPath,valueforkeypath

來源:互聯網
上載者:User

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部落格園看到本文,請點擊查看原文.

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.