处理stackviews上的多个轻击手势

时间:2019-09-12 01:41:34

标签: ios swift uitapgesturerecognizer uistackview

我有三个要添加轻击手势的堆栈视图,这是我的代码,但是我不得不一次又一次地复制相同的代码,很冷,您向我展示了一种更好的方法?

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)
}

非常感谢

1 个答案:

答案 0 :(得分:2)

您可以使用字典将UIStackView映射到segue identifier,然后使用单个handleTap()例程使用以下命令查找identifierview关联的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)
}