前言:好久没写博客,今天来一波。我在实际项目开发中,会遇到这样功能需求:我已经搭好了iOS的UI界面,但是很多界面的子View用了UIView,然后这些UIView中用了UILabel和UIImageView,然后接着需求要这些View能够有点击事件,比如一点击就跳转到某个控制器。一开始懵逼了,难道我还要把他们全部改成UIButton,但是UIButton不好添加子View,难道我还要全部自定义一下UIButton,就算自定义好了,在项目已经打好的界面还是要一个个替换,多麻烦。所以就想到通过UIView拓展类别,类别中的方法提供手势点击事件的监听,通过block传递事件任务。可是类别声明的属性没用,但是没关系,只好用上runtime运行时了。
代码如下:
UIView+AddClickedEvent.h
1 // 2 // UIView+AddClickedEvent.h 3 // AddClickedEvent 4 // 5 // Created by HEYANG on 16/6/6. 6 // Copyright © 2016年 HeYang. All rights reserved. 7 // 8 // github:https://github.com/HeYang123456789 9 // blog :http://www.cnblogs.com/goodboy-heyang10 //11 12 13 #import14 15 @interface UIView (AddClickedEvent)16 17 - (void)addClickedBlock:(void(^)(id obj))tapAction;18 19 @end
UIView+AddClickedEvent.m
1 // 2 // UIView+AddClickedEvent.m 3 // AddClickedEvent 4 // 5 // Created by HEYANG on 16/6/6. 6 // Copyright © 2016年 HeYang. All rights reserved. 7 // 8 // github:https://github.com/HeYang123456789 9 // blog :http://www.cnblogs.com/goodboy-heyang10 //11 12 13 #import "UIView+AddClickedEvent.h"14 #import15 16 @interface UIView ()17 18 @property void(^clickedAction)(id);19 20 @end21 22 23 @implementation UIView (AddClickedEvent)24 25 - (void)setClickedAction:(void (^)(id))clickedAction{26 objc_setAssociatedObject(self, @"AddClickedEvent", clickedAction, OBJC_ASSOCIATION_COPY_NONATOMIC);27 }28 29 - (void (^)(id))clickedAction{30 return objc_getAssociatedObject(self, @"AddClickedEvent");31 }32 33 - (void)addClickedBlock:(void(^)(id obj))clickedAction{34 self.clickedAction = clickedAction;35 // hy:先判断当前是否有交互事件,如果没有的话。。。所有gesture的交互事件都会被添加进gestureRecognizers中36 if (![self gestureRecognizers]) {37 self.userInteractionEnabled = YES;38 // hy:添加单击事件39 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];40 [self addGestureRecognizer:tap];41 }42 }43 44 - (void)tap{45 if (self.clickedAction) {46 self.clickedAction(self);47 }48 }49 50 51 @end
然后在Demo中实现这个效果,百度云链接: 密码: waq8