Search code examples
iosswiftuitapgesturerecognizer

Swift - How to add tap gesture to array of UIViews?


Looking to add a tap gesture to an array of UIViews - without success. Tap seems not to be recognised at this stage.

In the code (extract) below: Have a series of PlayingCardViews (each a UIView) showing on the main view. Brought together as an array: cardView. Need to be able to tap each PlayingCardView independently (and then to be able to identify which one was tapped).

@IBOutlet private var cardView: [PlayingCardView]!


override func viewDidLoad() {
    super.viewDidLoad()
    let tap = UITapGestureRecognizer(target: self, action: #selector(tapCard(sender: )))
    for index in cardView.indices {
        cardView[index].isUserInteractionEnabled = true
        cardView[index].addGestureRecognizer(tap)
        cardView[index].tag = index
    }
}

@objc func tapCard (sender: UITapGestureRecognizer) {
    if sender.state == .ended {
        let cardNumber = sender.view.tag
        print("View tapped !")
    }
}

Solution

  • You need

    @objc func tapCard (sender: UITapGestureRecognizer) { 
         let clickedView = cardView[sender.view!.tag] 
         print("View tapped !" , clickedView ) 
    }
    

    No need to check state here as the method with this gesture type is called only once , also every view should have a separate tap so create it inside the for - loop

    for index in cardView.indices  { 
       let tap = UITapGestureRecognizer(target: self, action: #selector(tapCard(sender: )))