iOSリスニングコントロールの属性の変更observeValueForKeyPath

4368 ワード


テストの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

 
もしあなたがwb 145230ブログ園でこの文章を見なかったら、テキストを表示するにはクリックしてください.