我有三个要添加轻击手势的堆栈视图,这是我的代码,但是我不得不一次又一次地复制相同的代码,很冷,您向我展示了一种更好的方法?
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)
}
非常感谢
答案 0 :(得分:2)
您可以使用字典将UIStackView
映射到segue
identifier
,然后使用单个handleTap()
例程使用以下命令查找identifier
与view
关联的UITapGestureRecognizer
:
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)
}