swift Uivew 添加点击事件

2021-07-08  本文已影响0人  大鹏你我他

    privatestructAssociateKeys {

        staticvargestureKey ="gestureKey"

        staticvartapBlock ="tapBlock"

    }

    func yx_setTapActionWithBlock(tapBlock:@escaping() ->Void){

        self.isUserInteractionEnabled = true

        var tapGesture = objc_getAssociatedObject(self, &AssociateKeys.gestureKey) as? UITapGestureRecognizer

        if(tapGesture==nil){

            tapGesture =UITapGestureRecognizer.init(target:self, action:#selector(handleActionForTapGesture(_:)))

            tapGesture!.numberOfTapsRequired=1

            self.addGestureRecognizer(tapGesture!)

            objc_setAssociatedObject(self, &AssociateKeys.gestureKey, tapGesture, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)

        }

        objc_setAssociatedObject(self, &AssociateKeys.tapBlock, tapBlock, .OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    }

    @objcfunchandleActionForTapGesture(_gesture:UITapGestureRecognizer) {

        lettapBlock =objc_getAssociatedObject(self, &AssociateKeys.tapBlock)as? () ->Void

        if(tapBlock!=nil) {

            tapBlock!()

        }

    }

上一篇下一篇

猜你喜欢

热点阅读