zoukankan      html  css  js  c++  java
  • 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博客园看到本文,请点击查看原文.

  • 相关阅读:
    Mongodb常用操作(转载)
    java中对象转换工具类,很好用
    IDEA中配置tomcat出现乱码的解决
    小山博客--面试题答案
    Redis简单配置和使用
    线程的控制和线程池
    进程与线程详细解释
    Quartz .Net(定时框架):
    C#面向对象几组关键字的详解(this,base,dynamic,var,const,readonly,is,as)
    C#设计模式--抽象工厂模式(创建型模式)
  • 原文地址:https://www.cnblogs.com/wb145230/p/4610017.html
Copyright © 2011-2022 走看看