Search code examples
xcodeimageviewuigesturerecognizeruitapgesturerecognizer

Make an image clickable to expand


I have a background image that I would like to expand when clicked. I have setup animations that will dim the background and prop the image to the center, but for some reason the image is not clickable.

I have tried to implement a simple print(tapped) and when I tap I dont see anything as well. I am wondering if I have to declare my image view as something else?

import Foundation
import UIKit

class JobViewController: UIViewController {


let imageView: UIImageView = {
    let iv = UIImageView(image: #imageLiteral(resourceName: "yo"))
    iv.contentMode = .scaleAspectFill
    iv.isUserInteractionEnabled = true
    iv.translatesAutoresizingMaskIntoConstraints = false
    iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleZoomTap)))
    return iv
}()

@objc func handleZoomTap(_ tapGesture: UITapGestureRecognizer) {
  print("tap tap")

}

override func viewDidLoad() {
    super.viewDidLoad()

     view.addSubview(imageView)
    imageView.fillSuperview()        

}
}

When I tap the image, I expect that it should at least print "tap tap" Is there something else that i am missing?


Solution

  • Delete this line:

    iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleZoomTap)))
    

    And add this to your viewDidLoad:

    imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleZoomTap)))