Search code examples
iosswiftuitapgesturerecognizer

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?


Solution

  • 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)        
    }