直接上代码
.h文件
#import <UIKit/UIKit.h>
typedef void (^btnBlock)();
@interfce UIButton (Block)
- (void)handelWithBlock:(btnBlock)block;
@end
.m文件
#import "UIButton+Block.h"
#import <objc/runtime.h>
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 <objc/runtime.h>