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)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/259762.html
標籤:其他
