1

I have 2 UIImageView and a single tapGestureRecognizer.

 override func viewDidLoad() {
        // Do any additional setup after loading the view.

        super.viewDidLoad()

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(cameraTapped(tapGestureRecognizer:)))

        cameraUIImageView.isUserInteractionEnabled = true
        cameraUIImageView.addGestureRecognizer(tapGestureRecognizer)

        plus1UIImageView.isUserInteractionEnabled = true
        plus1UIImageView.addGestureRecognizer(tapGestureRecognizer)
//        


    }

I can only tap on the second UIImageView, which is plus1UIImageView.

Why?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
John
  • 3,888
  • 11
  • 46
  • 84

3 Answers3

5

A UIGestureRecognizer must be used with a single view only. You are using same object for both views. Try this.

override func viewDidLoad() {
    // Do any additional setup after loading the view.

    super.viewDidLoad()

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(cameraTapped(tapGestureRecognizer:)))

    cameraUIImageView.isUserInteractionEnabled = true
    cameraUIImageView.addGestureRecognizer(tapGestureRecognizer)


    let tapGestureRecognizer2 = UITapGestureRecognizer(target: self, action: #selector(cameraTapped(tapGestureRecognizer:)))

    plus1UIImageView.isUserInteractionEnabled = true
    plus1UIImageView.addGestureRecognizer(tapGestureRecognizer2)        
}
Bilal
  • 18,478
  • 8
  • 57
  • 72
1

You can only add a gesture recognizer to one view, so when you add it to the second it's getting removed from the first. More in depth answer here:

Can you attach a UIGestureRecognizer to multiple views?

Kyle Somers
  • 614
  • 1
  • 8
  • 21
0

As all ans stated you can only add a gesture recognizer to one view. Although if both of your imageviews in same super view you can add tap gesture to their superview and access its subviews. You can check for tapped subview and take reference of tapped imageview using hitTest: method. Check my previous ans here. Do let me know if you have any queries in comment.

luckyShubhra
  • 2,731
  • 1
  • 12
  • 19