Search code examples
iosswiftuitapgesturerecognizer

How do I listen to tap gestures on different controls in the same view?


I have two copies of a control (its called a RatingControl). How do I write handlers that can be invoked on the correct object when somebody double taps on them?

I have:

@IBOutlet weak var ratingControl: RatingControl!
@IBOutlet weak var ratingControl2: RatingControl!

inside a TableViewController and then

override func viewDidLoad() {
    super.viewDidLoad()

    let tapGR = UITapGestureRecognizer(target: ratingControl, action: #selector(RatingControl.doubleTap(_:)))
    tapGR.numberOfTapsRequired = 2
    self.view.addGestureRecognizer(tapGR)

    let tapGR2 = UITapGestureRecognizer(target: ratingControl2, action: #selector(RatingControl.doubleTap(_:)))
    tapGR2.numberOfTapsRequired = 2
    self.view.addGestureRecognizer(tapGR2)

}

RatingControl.doubleTap(_) is an innocuous event handler.

When there is a double tap on the second rating control, the doubleTap method is called but is dispatched on the first rating control object!

I have tried setting two targets on a single UITapGestureRecognizer but it runs into the same problem.

Thanks much!


Solution

  • You need to add the gesture recognizers to the two rating controls instead of to self.view.

    Try this:

    let tapGR = UITapGestureRecognizer(target: self, action: #selector(RatingControl.doubleTap(_:)))
    tapGR.numberOfTapsRequired = 2
    ratingControl.addGestureRecognizer(tapGR) // ratingControl, not self.view
    let tapGR2 = UITapGestureRecognizer(target: self, action: #selector(RatingControl.doubleTap(_:))) 
    tapGR2.numberOfTapsRequired = 2
    ratingControl2.addGestureRecognizer(tapGR2) // ratingControl2, not self.view