您的位置:首页 > 产品设计 > UI/UE

封装-给继承自UIView的控件添加点击事件

2017-06-29 16:27 375 查看
在实际开发中,可能会需要给UILabel、UIView等等添加点击事件,目的就是在保留控件自身属性的同时,多一个点击效果,所以这里写了一个UIView的category,用于处理这种情况。

1、.h文件代码如下:

#import <UIKit/UIKit.h>

typedef void (^WhenTappedBlock)();

@interface UIView (Tapped) <UIGestureRecognizerDelegate>
/*!
@method
@abstract 单击
@param block 代码块
*/
- (void)whenTapped:(WhenTappedBlock)block;

@end


这里声明了一个block,用于在添加点击事件时,直接在block回调里面处理点击的响应事件。

2、.m文件主要代码如下:

#import "UIView+Tapped.h"
#import <objc/runtime.h>

@implementation UIView (Tapped)

static char kWhenTappedBlockKey;

#pragma mark - Set blocks
- (void)setBlock:(WhenTappedBlock)block forKey:(void *)blockKey {
self.userInteractionEnabled = YES;
objc_setAssociatedObject(self, blockKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void)runBlockForKey:(void *)blockKey {
WhenTappedBlock block = objc_getAssociatedObject(self, blockKey);
if (block) block();
}

#pragma mark - When Tapped
- (void)whenTapped:(WhenTappedBlock)block {
//添加点击手势
UITapGestureRecognizer* gesture = [self addTapGestureRecognizerWithTaps:1 touches:1 selector:@selector(viewWasTapped)];
[self addGestureRecognizer:gesture];
[self setBlock:block forKey:&kWhenTappedBlockKey];

}

/*手势点击响应事件*/
- (void)viewWasTapped {
[self runBlockForKey:&kWhenTappedBlockKey];
}

#pragma mark - addTapGesture
- (UITapGestureRecognizer*)addTapGestureRecognizerWithTaps:(NSUInteger)taps touches:(NSUInteger)touches selector:(SEL)selector {

UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:selector];
tapGesture.delegate = self;
tapGesture.numberOfTapsRequired = taps;
tapGesture.numberOfTouchesRequired = touches;

return tapGesture;
}

@end


这里用到了一个runtime的方法处理block。当然也可以不必像上面那样,可以通过delegate实现。这里只是一个思路,记录一下。

调用的时候也是非常方便,在要实现的地方添加#import “UIView+Tapped.h”,然后在初始化控件的地方添加如下代码即可:

[label whenTapped:^{
//这里添加点击响应的方法
}];


下面是demo里的测试效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息