星空网 > 软件开发 > 操作系统

UIButton+Block

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是动态创建的,且事件处理逻辑较少(比如就几行代码 ),我觉得还是可以使用。我目前是用在自定义导航栏按钮上。

 



原标题:UIButton+Block

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流