让你的UIButton自带block
#import "UIButton+CQBlock.h"
#import typedef void(^CQ_ButtonEventsBlock)(void);
@interface UIButton ()
/** 事件回调的block */
@property (nonatomic, copy) CQ_ButtonEventsBlock cq_buttonEventsBlock;
@end
@implementation UIButton (CQBlock)
//------- 添加属性 -------//
static void *cq_buttonEventsBlockKey = &cq_buttonEventsBlockKey;
- (CQ_ButtonEventsBlock)cq_buttonEventsBlock {
return objc_getAssociatedObject(self, &cq_buttonEventsBlockKey);
}
- (void)setCq_buttonEventsBlock:(CQ_ButtonEventsBlock)cq_buttonEventsBlock {
objc_setAssociatedObject(self, &cq_buttonEventsBlockKey, cq_buttonEventsBlock, OBJC_ASSOCIATION_COPY);
}
/**
给按钮绑定事件回调block
@param block 回调的block
@param controlEvents 回调block的事件
*/
- (void)cq_addEventHandler:(void (^)(void))block forControlEvents:(UIControlEvents)controlEvents {
self.cq_buttonEventsBlock = block;
[self addTarget:self action:@selector(cq_blcokButtonClicked) forControlEvents:controlEvents];
}
// 按钮点击
- (void)cq_blcokButtonClicked {
if (self.cq_buttonEventsBlock) {
self.cq_buttonEventsBlock();
}
}
@end
使用:
[button cq_addEventHandler:^{
NSLog(@"按钮点击");
}
方法命名我是模仿的BlocksKit:
[button bk_addEventHandler:^(id sender) {
NSLog(@"按钮点击");
}
然后所有button都带有block了,用起来和BlocksKit感觉一样。
这样就以很小的改动替换了RAC。
其实本质就是利用category和runtime给UIButton添加了一个block属性,单击的时候回调这个block