Search code examples
iosswiftuitapgesturerecognizer

tapGesture not being executed


I have added a tapGesture to my UIImageView rDot. The problem is when I tap on rDot nothing happens and it doesn't print "It worked". rDot is in a stack view with other elements, I don't know if that has anything to do with it not working. rDot and redDot are two separate UIImageViews.

 override func viewDidLoad() {
    super.viewDidLoad()

        rDot.isUserInteractionEnabled = true
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(rdotimageTapped(tapGestureRecognizer:)))
        rDot.addGestureRecognizer(tapGestureRecognizer)                        
}

func rdotimageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
        whiteD?.isHidden = true
        redDot?.isHidden = false
        print("It worked")
    }

Solution

  • You need to bring the subView to front since you have put the imageView within stackView. Sometimes the view hierarchy does not recognize the tapped subviews.

    override func viewDidLoad() {
        super.viewDidLoad()
    
        rDot.isUserInteractionEnabled = true
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(rdotimageTapped(tapGestureRecognizer:)))
        rDot.addGestureRecognizer(tapGestureRecognizer) 
        view.bringSubview(toFront: rDot)                
    }