UIButton+ZJBlock.h
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
NS_ASSUME_NONNULL_BEGIN
typedef void(^ActionBlock)(void);
@interface UIButton (ZJBlock)
- (void)handleEvent:(UIControlEvents)controlEvent withBlock:(ActionBlock)action;
@end
NS_ASSUME_NONNULL_END
UIButton+ZJBlock.m
#import "UIButton+ZJBlock.h"
static char touchKey;
@implementation UIButton (ZJBlock)
- (void)handleEvent:(UIControlEvents)controlEvent withBlock:(ActionBlock)action{
objc_setAssociatedObject(self,&touchKey,action,OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(callActionBlock:) forControlEvents:controlEvent];
}
- (void)callActionBlock:(id)sender{
ActionBlock block = (ActionBlock)objc_getAssociatedObject(self,&touchKey);
if(block){
block();
}
}
@end
调用方式
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(100,100,100,44);
btn.backgroundColor = [UIColor blackColor];
[self.view addSubview:btn];
[btn handleEvent:UIControlEventTouchUpInside withBlock:^{
NSLog(@"点击了");
}];