美文网首页
iOS给UIView添加点击事件

iOS给UIView添加点击事件

作者: HCL黄 | 来源:发表于2019-10-14 15:49 被阅读0次

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

    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    [self.view addGestureRecognizer:gesture];
    
    - (void)tapGesture:(UITapGestureRecognizer *)gesture {
        NSLog(@"点击了");
    }
    

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

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

    • 首先创建一个UIView的分类文件,并在分类里动态添加一个点击事件的方法
    @interface UIView (Extension)
    
    - (void)setTapActionWithBlock:(void (^)(void))block;
    
    @end
    
    • 在.m文件实现这个方法
    
    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
    

    接下来就可以直接使用了

    • 导入头文件 #import "UIView+Extension.h"
    • 在需要添加事件的UIView直接setTapActionWithBlock
    @weakify(self);
    [self.tempView setTapActionWithBlock:^{
        @strongify(self);
        NSLog(@"点击了 = %@", self.tempView);
    }];
    

    相关文章

      网友评论

          本文标题:iOS给UIView添加点击事件

          本文链接:https://www.haomeiwen.com/subject/euwlmctx.html