iOS给UIView添加点击事件

2019-10-14  本文已影响0人  HCL黄

通常我们需要给一个UIView添加点击事件,最简单的做法是

UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
[self.view addGestureRecognizer:gesture];

- (void)tapGesture:(UITapGestureRecognizer *)gesture {
    NSLog(@"点击了");
}

假如要给几十、几百个UIView添加点击事件,那上面的方法就显得有点恶心了,即使抽出一个公共方法,也会觉得有点low

接下来我们用一个比较高级的方法(运行时动态添加方法)来给UIView添加点击事件

@interface UIView (Extension)

- (void)setTapActionWithBlock:(void (^)(void))block;

@end

static char kLAActionHandlerTapGestureKey;
static char kLAActionHandlerTapBlockKey;

@implementation UIView (Extension)

- (void)setTapActionWithBlock:(void (^)(void))block {
    // 运行时获取单击对象
    UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &kLAActionHandlerTapGestureKey);
    if (!gesture) {
        // 如果没有该对象,就创建一个
        gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleActionForTapGesture:)];
        [self addGestureRecognizer:gesture];
        // 绑定一下gesture
        objc_setAssociatedObject(self, &kLAActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
    }
    // 绑定一下block
    objc_setAssociatedObject(self, &kLAActionHandlerTapBlockKey, block, OBJC_ASSOCIATION_COPY);
}

- (void)handleActionForTapGesture:(UITapGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateRecognized) {
        // 取出上面绑定的block
        void(^action)(void) = objc_getAssociatedObject(self, &kLAActionHandlerTapBlockKey);
        if (action) {
            action();
        }
    }
}

@end

接下来就可以直接使用了

@weakify(self);
[self.tempView setTapActionWithBlock:^{
    @strongify(self);
    NSLog(@"点击了 = %@", self.tempView);
}];
上一篇 下一篇

猜你喜欢

热点阅读