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