转自:传送门
写此文章只是为了以后我自己能更方便的复制粘贴.😁😆😆
上代码
.h文件
#import <UIKit/UIKit.h>
typedef void(^ButtonClick/*这里名字随意起,但是下面使用到的需要名字一致*/)(UIButton *button);
@interface UIButton (BtnClick)
/**
* 添加点击事件
*/
- (void)addClick:(ButtonClick/*这里名字与block名字一致*/)block;
/**
* 可以自定义事件
*/
- (void)addAction:(ButtonClick/*这里名字与block名字一致*/)block forControlEvents:(UIControlEvents)controlEvents;
@end
.m文件
#import "BtnClick.h"
#import <objc/runtime.h>
@implementation UIButton (BtnClick)
static char ActionTag;
- (void)addClick:(ButtonClick/*这里名字与block名字一致*/)block {
[self addAction:block forControlEvents:UIControlEventTouchUpInside];
}
- (void)addAction:(ButtonClick/*这里名字与block名字一致*/)block forControlEvents:(UIControlEvents)controlEvents {
objc_setAssociatedObject(self, &ActionTag, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(action:) forControlEvents:controlEvents];
}
- (void)action:(id)sender {
ButtonClick/*这里名字与block名字一致*/ blockAction = (ButtonClick/*这里名字与block名字一致*/)objc_getAssociatedObject(self, &ActionTag);
if (blockAction) {
blockAction(self);
}
}
@end
只是为了方便,嗯,就是这样.直接复制粘贴即可~