1.使用runtime机制中的objc_setAssociatedObject和objc_getAssociatedObject方法
@interface UIButton (LXAdd)
- (void)addTargetEvents:(UIControlEvents)Events block:(void (^)(id sender))block;
@end
@implementation UIButton (LXAdd)
- (void)invoke:(id)sender {
void (^block)(id sender) = objc_getAssociatedObject(self, &block_key);
block(sender);
}
- (void)addTargetEvents:(UIControlEvents)Events block:(void (^)(id sender))block{
if(!Events) return;
objc_setAssociatedObject(self, &block_key, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self addTarget:self action:@selector(invoke:) forControlEvents:Events];
}
@end