处理堆栈视图上的多次点击手势

Handle multiple tap gesture on stackviews

我有三个堆栈视图,我想添加点击手势,这是我的代码,但我必须一次又一次地复制相同的代码,你能告诉我更好的方法吗?

func addTapGestureToInformationLables(){
    let tapLanguage = UITapGestureRecognizer(target: self, action: #selector(self.handleTapLanguage(_:)))
    languageStack.addGestureRecognizer(tapLanguage)
    let tapFollower = UITapGestureRecognizer(target: self, action: #selector(self.handleFollowers(_:)))
    followrsStack.addGestureRecognizer(tapFollower)
    let tapFollowing = UITapGestureRecognizer(target: self, action: #selector(self.handleFollowing(_:)))
    followingStack.addGestureRecognizer(tapFollowing)
}



@objc func handleTapLanguage(_ sender: UITapGestureRecognizer? = nil) {
        performSegue(withIdentifier: "language", sender: nil)
}


@objc func handleFollowers(_ sender: UITapGestureRecognizer? = nil) {
    performSegue(withIdentifier: "followers", sender: nil)
}


@objc func handleFollowing(_ sender: UITapGestureRecognizer? = nil) {
    performSegue(withIdentifier: "following", sender: nil)
}

非常感谢

您可以使用字典将 UIStackView 映射到 segue identifier,然后使用单个 handleTap() 例程查找 identifier使用与 UITapGestureRecognizer:

关联的 view
var actions = [UIStackView : String]()

func addTapGestureToInformationLables(){
    actions = [languageStack: "language", followrsStack: "followers", followingStack: "following"]

    for stackview in actions.keys {
        let recognizer = UITapGestureRecognizer(target, self, action: #selector(self.handleTap))
        stackview.addGestureRecognizer(recognizer)
    }
}   

@objc func handleTap(_ sender: UITapGestureRecognizer) {
    guard let stackview = sender.view as? UIStackView,
          let identifier = actions[stackview]
        else { return }

    performSegue(withIdentifier: identifier, sender: nil)
}