swift 5 中如何使用关联给所有Uivew子类添加tap事件

 

 

Uiew+Tap.swift

 

//
//  Uiew+Tap.swift
//  YYYSwiftProductTh
//
//  Created by YYY on 2021/2/13.
//

import Foundation
import UIKit



typealias clickViewEventBlock = (_ sender: UIView)->()


//作用相当于给view加一个属性:手势的点击事件
private var AssociatedBlockHandle: clickViewEventBlock?


//作用相当于给view加一个属性:手势
private var AssociatedTapHandle: UITapGestureRecognizer?




extension UIView {

    @objc private func clickViewEvent(sender:UITapGestureRecognizer){

        //取属性:手势
       guard let block = objc_getAssociatedObject(self, &AssociatedTapHandle) as? clickViewEventBlock else { return }

       block(sender.view!)

    }
    
    //外部调用
    func clickView(action: clickViewEventBlock?) {

        //取属性:手势的点击事件
        var tap = objc_getAssociatedObject(self, &AssociatedBlockHandle)
        
        if tap == nil {
            
            
            tap = UITapGestureRecognizer(target: self, action: #selector(clickViewEvent(sender:)))
            
            self.addGestureRecognizer(tap as! UIGestureRecognizer)
            
            //设置属性:手势的点击事件
            objc_setAssociatedObject(self, &AssociatedBlockHandle, tap, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)

        }
   
        //设置属性:手势
        objc_setAssociatedObject(self, &AssociatedTapHandle, action, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)

    }
    
    


}



 

 

 

你可能感兴趣的:(ios,关联,tap)