前言:好久没写博客,今天来一波。我在实际项目开发中,会遇到这样功能需求:我已经搭好了iOS的UI界面,但是很多界面的子View用了UIView,然后这些UIView中用了UILabel和UIImageView,然后接着需求要这些View能够有点击事件,比如一点击就跳转到某个控制器。一开始懵逼了,难道我还要把他们全部改成UIButton,但是UIButton不好添加子View,难道我还要全部自定义一下UIButton,就算自定义好了,在项目已经打好的界面还是要一个个替换,多麻烦。所以就想到通过UIView拓展类别,类别中的方法提供手势点击事件的监听,通过block传递事件任务。可是类别声明的属性没用,但是没关系,只好用上runtime运行时了。
代码如下:
UIView+AddClickedEvent.h
//
// UIView+AddClickedEvent.h
// AddClickedEvent
//
// Created by HEYANG on 16/6/6.
// Copyright © 2016年 HeYang. All rights reserved.
//
// github:https://github.com/HeYang123456789
// blog :http://www.cnblogs.com/goodboy-heyang
// #import <UIKit/UIKit.h> @interface UIView (AddClickedEvent) - (void)addClickedBlock:(void(^)(id obj))tapAction; @end
UIView+AddClickedEvent.m
//
// UIView+AddClickedEvent.m
// AddClickedEvent
//
// Created by HEYANG on 16/6/6.
// Copyright © 2016年 HeYang. All rights reserved.
//
// github:https://github.com/HeYang123456789
// blog :http://www.cnblogs.com/goodboy-heyang
// #import "UIView+AddClickedEvent.h"
#import <objc/message.h> @interface UIView () @property void(^clickedAction)(id); @end @implementation UIView (AddClickedEvent) - (void)setClickedAction:(void (^)(id))clickedAction{
objc_setAssociatedObject(self, @"AddClickedEvent", clickedAction, OBJC_ASSOCIATION_COPY_NONATOMIC);
} - (void (^)(id))clickedAction{
return objc_getAssociatedObject(self, @"AddClickedEvent");
} - (void)addClickedBlock:(void(^)(id obj))clickedAction{
self.clickedAction = clickedAction;
// hy:先判断当前是否有交互事件,如果没有的话。。。所有gesture的交互事件都会被添加进gestureRecognizers中
if (![self gestureRecognizers]) {
self.userInteractionEnabled = YES;
// hy:添加单击事件
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
[self addGestureRecognizer:tap];
}
} - (void)tap{
if (self.clickedAction) {
self.clickedAction(self);
}
} @end
然后在Demo中实现这个效果,百度云链接: http://pan.baidu.com/s/1jHQkWMa 密码: waq8