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
?
Adding a Tap Gesture Recognizer in Interface Builder You don't need to switch between the code editor and Interface Builder. Open Main. storyboard and drag a tap gesture recognizer from the Object Library and drop it onto the view we added earlier. The tap gesture recognizer appears in the Document Outline on the left.
The iOS UITapGestureRecognizer class has a built-in way to detect a double tap on any view. All you need to do is create the recognizer, set its numberOfTapsRequired property to 2, then add it to the view you want to monitor.
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
)
You need to add a a gesture recognizer (For tap use UITapGestureRecognizer, for tap and hold use UILongPressGestureRecognizer) to your UIImageView
.
let tap = UITapGestureRecognizer(target: self, action: #selector(YourClass.tappedMe))
imageView.addGestureRecognizer(tap)
imageView.isUserInteractionEnabled = true
And Implement the selector method like:
@objc func tappedMe()
{
println("Tapped on Image")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With