ios - 如何使用 swift 为 UITapGestureRecognizer 编写通用方法

标签 ios swift uitapgesturerecognizer

我必须为标签和 ImageView 添加 tapGesture。如何为 Labels 和 ImageView 创建通用的点击手势方法?

//TapGestureHandler
extension EditViewController : UIGestureRecognizerDelegate
{
 //Add Gesture on ImageView
 func addGesture()
 {
    //Gesture Male
    let maleTapGesture = UITapGestureRecognizer(target: self, action: #selector(maleGestureTap))
    maleTapGesture.delegate = self
    imgViewMale.addGestureRecognizer(maleTapGesture)

    //GestureFemale
    let FemaleTapGesture = UITapGestureRecognizer(target: self, action: #selector(femaleGestureTap))
    FemaleTapGesture.delegate = self
    imgViewFemale.addGestureRecognizer(FemaleTapGesture)

    //Gesture MaleFemale
    let maleFeTapGesture = UITapGestureRecognizer(target: self, action: #selector(maleFeGestureTap))
    maleFeTapGesture.delegate = self
    imgViewMaleFe.addGestureRecognizer(maleFeTapGesture)
 }

 //Tap Gesture Male
 func maleGestureTap()
 {
    imgViewMale.backgroundColor = hexStringToUIColor(hex: "#CBFFE2")
 }

 //Tap Gesture Female
 func femaleGestureTap()
 {
    imgViewFemale.backgroundColor = hexStringToUIColor(hex: "#CBFFE2")
 }

 //Tap Gesture MaleFemale
 func maleFeGestureTap()
 {
    imgViewMaleFe.backgroundColor = hexStringToUIColor(hex: "#CBFFE2")
 }
}

我不知道我们怎么能写一个泛型方法。

最佳答案

你可以这样做:

假设您有一些对象需要附加点击处理程序,假设它们都符合 UIView 协议(protocol):

let subviews: [Any] = [label1, label2, label3, view1, imageview1]()
label1.tag = 1 //** add a tag to your object **
for v in subviews {
   self.addTapGesture(to: v)
}

 func tapped(_ sender: UITapGestureRecognizer) {
    print("tapped")
    if sender.view?.tag == 1 {
        // *** this is your label1 view ***
    }
}

func addTapGesture(to: Any?) {
    if let v = to as? UIView {
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapped(_:)))
        v.addGestureRecognizer(tapGesture)
        v.isUserInteractionEnabled = true
    }
}

关于ios - 如何使用 swift 为 UITapGestureRecognizer 编写通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41311925/

相关文章:

ios - 点击手势错误,在错误的 View 中识别点击

iphone - 如何在应用商店中找到应用下载日期?

ios - 如何在 NSBundle 中从 Assets.car(xcassets 的编译版本)加载图像?

swift - 如何向已安装的 pod xcode 添加额外文件

swift - UITableView 和可重用单元格的问题

ios - 如何检测来自 uiwebview 或 self.view 的点击手势?

ios - 无法触摸包含 AVPlayerLayer 的 UIView

ios - PhoneGap iOS 提交错误 : ITMS-90807: Invalid entitlement - How can I build with SDK 13 or later?

ios - 如何获取 UITextView 中最后一行的文本长度

ios - 苹果HLS离线视频播放如果网络不可用则无法播放2个视频