美文网首页BUTTON
iOS-给button分类添加点击事件block属性

iOS-给button分类添加点击事件block属性

作者: malgee | 来源:发表于2018-12-16 20:37 被阅读21次

    分类属性

    @property (nonatomic, copy) void(^clickAction)(UIButton *button);
    
    static char *const kAction = "kAction";
    
    - (void)setClickAction:(void (^)(UIButton *))clickAction
    {
        objc_setAssociatedObject(self, kAction, clickAction, OBJC_ASSOCIATION_COPY_NONATOMIC);
        
        [self removeTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    
        if (clickAction) {
            
            [self addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        }  
    }
    
    - (void (^)(UIButton *))clickAction
    {
        return objc_getAssociatedObject(self, kAction);
    }
    
    - (void)buttonClick:(UIButton *)button
    {
        if (self.clickAction) {
            self.clickAction(button);
        }
    }
    

    这样就可以快速的给button添加点击事件

    相关文章

      网友评论

        本文标题:iOS-给button分类添加点击事件block属性

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