How to assign an action for UIImageView object in Swift

user3706773 picture user3706773 · Jan 10, 2015 · Viewed 157.9k times · Source

I'm trying to assign an UIImageView to an action when the user taps it.

I know how to create an action for a UIButton, but how could I mimic the same behavior of a UIButton, but using a UIImageView?

Answer

Aseider picture Aseider · Jan 10, 2015

You'll need a UITapGestureRecognizer. To set up use this:

override func viewDidLoad()
{
    super.viewDidLoad()

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

@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
    let tappedImage = tapGestureRecognizer.view as! UIImageView

    // Your action
}

(You could also use a UIButton and assign an image to it, without text and than simply connect an IBAction)