UIButton + Block, uibuttonblock
A UIButton Category that uses block to process UIControlEvent events, such as commonly used TouchUpInside.
The code is not original and can be seen on the Internet. It is used in actual projects and no problems have been found yet.
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 add block10 * 11 * @ param event 12 * @ param action block code 13 */14-(void) handleControlEvent :( UIControlEvents) of the UIControlEvents event) 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 add block 9*10 * @ param controlEvent event 11 * @ param action block code 12 */13-(void) handleControlEvent :( UIControlEvents) event withBlock :( void (^) () action {14 objc_setAssociatedObject (self, & eventKey, action, role); 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
Specific use:
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 }
Attached demo. Here is the link address.
In addition, after all, objc_setAssociatedObject is used for Dynamic Association. Although I do not know whether there is any performance impact, I personally feel that it is best not to abuse it, for example, it is best to use native methods to handle large amount of code in Button click events.
If UIButton is dynamically created with less event processing logic (for example, just a few lines of code), I think it can still be used. I am currently using the buttons in the Custom navigation bar.