UIButton的一個Category,使用block處理UIControlEvent事件,如常用的TouchUpInside等。
代碼非原創,也是從網上看到的,用到了實際項目中,目前還沒發現什麼問題。
UIButton+Block.h:
#import <UIKit/UIKit.h> #import <objc/runtime.h> typedef void (^ActionBlock)(); @interface UIButton (Block) /** * UIButton添加UIControlEvents事件的block * * @param event 事件 * @param action block代碼 */ - (void) handleControlEvent:(UIControlEvents)event withBlock:(ActionBlock)action; @end
UIButton+Block.m:
#import "UIButton+Block.h"
@implementation UIButton (Block)
static char eventKey;
/**
* UIButton添加UIControlEvents事件的block
*
* @param controlEvent 事件
* @param action block代碼
*/
- (void) handleControlEvent:(UIControlEvents)event withBlock:(void (^)())action {
objc_setAssociatedObject(self, &eventKey, action, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(callActionBlock:) forControlEvents:event];
}
- (void)callActionBlock:(id)sender {
ActionBlock block = (ActionBlock)objc_getAssociatedObject(self, &eventKey);
if (block) {
block();
}
}
@end
具體使用:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.button handleControlEvent:UIControlEventTouchUpInside withBlock:^{
NSLog(@"button touched!");
}];
}
附上demo,這裡是鏈接地址。
另外,畢竟是用到了objc_setAssociatedObject動態關聯,雖然不知道有沒有什麼性能影響,但是個人感覺最好不要濫用,比如Button的點擊事件裡代碼量較大時最好還是用原生的處理方法。
如果UIButton是動態創建的,且事件處理邏輯較少(比如就幾行代碼 ),我覺得還是可以使用。我目前是用在自定義導航欄按鈕上。