Search code examples
iosswiftuiimageviewuitapgesturerecognizer

UIImageView does not recognize my tap events


I have an UIImageView that I have created like this:

let tap = UITapGestureRecognizer(target: self, action: #selector(test))

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
imageView.image = UIImage(named: "Test")
imageView.addGestureRecognizer(tap)
self.view.addSubview(imageView)

But for somehow is does not call the test function when I click on it... Seems like I have tried everything but it does not work. Any suggestions why?


Solution

  • The UIImageView is by default set to have the isUserInteractionEnabled property to false, that means that you can´t interact with the UIImageView.

    Add this property and it will work:

    imageView.isUserInteractionEnabled = true