Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect UIImageView Touch in Swift

How would you detect and run an action when a UIImageView is touched? This is the code that I have so far:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 
    var touch: UITouch = UITouch()
    if touch.view == profileImage {
        println("image touched")
    }
}
like image 209
Stefan DeClerck Avatar asked Jun 22 '15 22:06

Stefan DeClerck


2 Answers

You can detect touches on a UIImageView by adding a UITapGestureRecognizer to it.

It's important to note that by default, a UIImageView has its isUserInteractionEnabled property set to false, so you must set it explicitly in storyboard or programmatically.


override func viewDidLoad() {
    super.viewDidLoad()

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

@objc private func imageTapped(_ recognizer: UITapGestureRecognizer) {
    print("image tapped")
}
like image 161
Justin Rose Avatar answered Oct 20 '22 18:10

Justin Rose


You can put an UITapGestureRecognizer inside your UIImageView using Interface Builder or in code (as you want), I prefer the first. Then you can put an @IBAction and handle the tap inside your UIImageView, Don't forget to set the UserInteractionEnabled to true in Interface Builder or in code.

@IBAction func imageTapped(sender: AnyObject) {
    println("Image Tapped.")
}

I hope this help you.

like image 22
Victor Sigler Avatar answered Oct 20 '22 18:10

Victor Sigler