美文网首页
Block扩展UIButton写法记录

Block扩展UIButton写法记录

作者: 码农_雷 | 来源:发表于2016-10-19 10:47 被阅读0次

    1.使用runtime机制中的objc_setAssociatedObject和objc_getAssociatedObject方法

    @interface UIButton (LXAdd)

      - (void)addTargetEvents:(UIControlEvents)Events block:(void (^)(id sender))block;
    

    @end

    @implementation UIButton (LXAdd)

    - (void)invoke:(id)sender {
       void (^block)(id sender) = objc_getAssociatedObject(self, &block_key);
        block(sender);
    }
    
    - (void)addTargetEvents:(UIControlEvents)Events block:(void (^)(id sender))block{
        if(!Events) return;
        objc_setAssociatedObject(self, &block_key, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [self addTarget:self action:@selector(invoke:) forControlEvents:Events];
    }
    

    @end

    相关文章

      网友评论

          本文标题:Block扩展UIButton写法记录

          本文链接:https://www.haomeiwen.com/subject/zrqxuttx.html