Search code examples
swiftuitapgesturerecognizer

Check which image view was pressed using UITapGestureRecognizer in Swift


I have three UITapGestureRecognizers.
They look like that:

gestureImageViewUp = UITapGestureRecognizer(target: self, action: #selector(ViewController.checkChoice(_:)))
self.imageViewUp.addGestureRecognizer(gestureImageViewUp)

gestureImageViewDown = UITapGestureRecognizer(target: self, action: #selector(ViewController.checkChoice(_:)))
self.imageViewDown.addGestureRecognizer(gestureImageViewDown)

gestureImageViewMiddle = UITapGestureRecognizer(target: self, action: #selector(ViewController.checkChoice(_:)))
self.imageViewMiddle.addGestureRecognizer(gestureImageViewMiddle)

I want to check which of them was pressed. How can I solve that?


Solution

  • You shouldn't need more then one recogniser, just attach it to the view and in the selector check which imageview was clicked.

    func onPress(_ guesture: UIGestureRecognizer) {
    
        guard let location = guesture.location(in: self.view)  else { return }
    
        if gestureImageViewUp.frame.contains(location) {
            // …
        }
        if gestureImageViewDown.frame.contains(location) {
            // …
        }
        if gestureImageViewMiddle.frame.contains(location) {
            // …
        }
    }
    

    Not tested sorry, it would be easier if you pasted code instead of snapshots