UIButton的点击事件使用block回调

直接上代码

.h文件
#import
typedef void (^btnBlock)();

@interfce UIButton (Block)

- (void)handelWithBlock:(btnBlock)block;

@end

.m文件

#import "UIButton+Block.h"
#import 

static const char btnKey;

@implementation UIButton (Block)

- (void)handelWithBlock:(btnBlock)block
{
    if (block)
    {
       set方法将self和block通过btnkey关联起来
        objc_setAssociatedObject(self, &btnKey, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }

    [self addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
}

- (void)btnAction
{
     get方法通过key获取对象
    btnBlock block = objc_getAssociatedObject(self, &btnKey);
    block();
}

@end

tips: 使用objc_setAssociatedObject,需要引入头文件 #import

你可能感兴趣的:(UIButton的点击事件使用block回调)