John John -3 years ago 117
iOS Question

one tap gesture on multiple UIImageView

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?

Answer Source

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)        
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download