Search code examples
iosswiftuitapgesturerecognizeruistackview

Handle multiple tap gesture on stackviews


I have three stackviews that I want to add tap gesture, here is my code, but I have to copy a same code again and again, cold you show me a better way to do that?

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

Many Thanks


Solution

  • You can use a dictionary to map the UIStackView to the segue identifier and then use a single handleTap() routine to look up the identifier using the view associated with the 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)
    }