iOS开发札记Swift开发札记

iOS 动分类添加手势(OC/Swift)

2018-06-02  本文已影响2人  小布走慢点

OC版本

我们在OC经常会有需求给UIView添加手势的功能我们可以给分类添加属性是这么写的,即使用Runtime中的objc_setAssociatedObjectobjc_getAssociatedObject

- (void)setClickedAction:(void (^)(id))clickedAction{
    objc_setAssociatedObject(self, @"AddClickedEvent", clickedAction, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void (^)(id))clickedAction{
    return objc_getAssociatedObject(self, @"AddClickedEvent");
}

- (void)addClickedBlock:(void(^)(id obj))clickedAction{
    self.clickedAction = clickedAction;
    if (![self gestureRecognizers]) {
        self.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bloodspasmTap)];
        [self addGestureRecognizer:tap];
    }
}

- (void)bloodspasmTap{
    if (self.clickedAction) {
        self.clickedAction(self);
    }
}

Swift版本

在Swift中如何实现objc_setAssociatedObjectobjc_getAssociatedObject

参考Swift3.0朝圣之路-使用Runtime在分类Extension中添加属性

func addClickedBlock(_ clickedAction: @escaping (_ obj: Any?) -> Void) {
        self.clickedAction = clickedAction
        self.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(self.bloodspasmTap))
        addGestureRecognizer(tap)
    }
    @objc func bloodspasmTap() {
        clickedAction!(self)
    }
    struct runtimeKey {
        static let clickedAction = UnsafeRawPointer.init(bitPattern: "AddClickedEvent".hashValue)
    }
    var clickedAction: ((_ obj: Any?) -> Void)? {
        set {
            objc_setAssociatedObject(self, UIView.runtimeKey.clickedAction!, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        get {
            return  objc_getAssociatedObject(self, UIView.runtimeKey.clickedAction!) as? ((_ obj: Any?) -> Void)
        }
    }
上一篇下一篇

猜你喜欢

热点阅读