UIButton 使用 Block 实现点击回调

引言:

通过分类,实现 Block 方式的 按钮点击回调效果。


# 一. 代码实现

UIButton+BlockOnClick.h 文件:


@interface UIButton (BlockOnClick)

/// 添加点击事件
- (void)lc_addTouchUpInsideBlock:(void(^)(UIButton *btn))block;

@end


UIButton+BlockOnClick.m 文件:
#pragma mark - ------ Block 方式点击回调 ------
@interface UIButton ()
@property (nonatomic, copy) void(^lc_block)(UIButton *);
@end

@implementation UIButton(BlockOnClick)
// runtime 方式添加属性
- (void)setLc_block:(void (^)(UIButton *))lc_block {
    objc_setAssociatedObject(self, @selector(lc_block), lc_block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void (^)(UIButton *))lc_block {
    return objc_getAssociatedObject(self, @selector(lc_block));
}


- (void)onClick:(UIButton *)btn {
    
    if (self.lc_block) {
        self.lc_block(btn);
    }
}


/// 添加点击事件
- (void)lc_addTouchUpInsideBlock:(void (^)(UIButton *))block {
    
    self.lc_block = block;
    [self addTarget:self action:@selector(onClick:) forControlEvents:(UIControlEventTouchUpInside)];
}

@end

# 二. 调用方式

    // 加载按钮
    UIButton *reloadBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.view addSubview:reloadBtn];
    
    // 点击事件
    [reloadBtn lc_addTouchUpInsideBlock:^(UIButton *btn) {
        
        // 移除
        [self.lc_placeholderV removeFromSuperview];
        self.lc_placeholderV = nil;
    }];