美文网首页
为UIView添加点击回调

为UIView添加点击回调

作者: 喵喵粉 | 来源:发表于2020-06-28 16:37 被阅读0次

    UIView添加手势使用block回调写法

    • .h
    #import <UIKit/UIKit.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface UIView (Action)
    - (void)extAction:(void (^)(void))action;
    @end
    
    NS_ASSUME_NONNULL_END
    
    • .m
    #import "UIView+Action.h"
    #import <objc/message.h>
    
    @interface UIView ()
    @property (nonatomic, copy) void (^action)(void);
    @end
    
    
    @implementation UIView (Action)
    
    - (void)setAction:(void (^)(void))action {
        objc_setAssociatedObject(self, @selector(action), action, OBJC_ASSOCIATION_COPY);
    }
    - (void (^)(void))action {
        return objc_getAssociatedObject(self, _cmd);
    }
    
    - (void)extAction:(void (^)(void))action {
        
        self.userInteractionEnabled = YES;
        
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(extAddTap)]];
        self.action = action;
    }
    
    - (void)extAddTap {
        if (self.action) {
            self.action();
        }
    }
    
    @end
    
    • vc调用
    - (void)test {
        [_vTest extAction:^{
            NSLog(@"tap1");
        }];
        
        __weak __typeof(self)weakSelf = self;
        [_ivTest extAction:^{
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            
        }];
    }
    

    相关文章

      网友评论

          本文标题:为UIView添加点击回调

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