How to add tapGesture for UIImageView in UIView

Viewed 6210

I am stuck in adding tap gesture recogniser for UIImageView in a UIView. I did put the isUserInteractionEnabled = true for both UIImageView And UIView. but it still not working.

@IBOutlet weak var adView: UIView!<br>
@IBOutlet weak var defaultBannerView: UIImageView!
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(FavouritesVC.tappedImageBanner(_:)))

defaultBannerView.addGestureRecognizer(tapGesture) defaultBannerView.isUserInteractionEnabled = true adView.isUserInteractionEnabled = true

 func tappedImageBanner(_ sender: UIGestureRecognizer){
    print("Tapped")
    let tappedImageView = sender.view!
    let imageView = tappedImageView as! UIImageView
    print(imageView) }

Edit:

I added adView.addGestureRecognizer(tapGesture) but the error is 'Could not cast value of type 'UIView' to 'UIImageView''

Actually I am doing admob, I want to put my default Banner when I can't request the banner from google admob. So I want user to able to click on my default banner and direct to the website. So should I just add the tapGesture in the adView and hide the imageView when I can get the ad from google?

what if I want to add gesture in UIImageView? how should I do that?

2 Answers
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)

func imageTapped(tapGestureRecognizer: UITapGestureRecognizer){

    let tappedImage = tapGestureRecognizer.view as! UIImageView

    // Your action 
}

I am stuck in adding tap gesture recogniser for UIImageView in a UIView. (...) but it still not working.

What does that mean: not working? I can assume that taps are not detected.

I added adView.addGestureRecognizer(tapGesture) but the error is 'Could not cast value of type 'UIView' to 'UIImageView''

When the error happens? I assume that it comes when adView is tapped, so that because your sender.view! is not a UIImageView (in case gesture recogniser is linked to UIView).

I want to put my default Banner when I can't request the banner from google admob. (...) So should I just add the tapGesture in the adView and hide the imageView when I can get the ad from google? What if I want to add gesture in UIImageView?

Have you ever considered adding UIImageView above UIView and change its alpha to 0 or hide when Banner is loaded - it prevents imageView from being tapped?

Actually I am doing admob (...) I Added a custom UIView called adView (...) it won't allow me to touch the defaultBannerView

As you say, you are adding imageView to custom view and you don't know how it really works. Think if you really need to interfere with its logic.

Related