类目:将TapGesture封装成一个block

上代码.h文件

#import 
NS_ASSUME_NONNULL_BEGIN
typedef void(^MyTapGestureRecognizerBlock)();
@interface UIView (TapGestureRecognize)
/**
 *  可用来重新设置点击事件的方法
 */
@property (nonatomic, copy) MyTapGestureRecognizerBlock gestureBlock;
/**
 *  给视图添加一个点击事件
 *  @param action 实现点击事件的方法
 */
- (void)addGestureRecognizerAtction:(MyTapGestureRecognizerBlock __nonnull)action;
@end
NS_ASSUME_NONNULL_END

.m文件

#import "UIView+TapGestureRecognize.h"
#import 
#import 

@implementation UIView (TapGestureRecognize)

#pragma mark - 动态生成属性
static char gestureBlockKey;
@dynamic gestureBlock;

- (void)setGestureBlock:(MyTapGestureRecognizerBlock)gestureBlock {
    objc_setAssociatedObject(self, &gestureBlockKey, gestureBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (MyTapGestureRecognizerBlock)gestureBlock {
    return objc_getAssociatedObject(self, &gestureBlockKey);
}

#pragma mark - 实现功能方法
- (void)addGestureRecognizerAtction:(MyTapGestureRecognizerBlock)action {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleMyTapGestureRecognizer)];
    [self addGestureRecognizer:tap];
    self.gestureBlock = action;
    self.userInteractionEnabled = YES;
}

- (void)handleMyTapGestureRecognizer {
    static double preClickTime = -1;
    double curClickTime = [[NSDate date] timeIntervalSince1970];
    if ((curClickTime - preClickTime) > 0.2) {
        self.gestureBlock();
    }
    preClickTime = curClickTime;
}
@end

你可能感兴趣的:(类目:将TapGesture封装成一个block)