Add action to an UIImageView?

Hey there,

it is possible to add an action to an UIImageView?
Or do I have to place a button around it?
Answered by OOPer in 619160022
What sort of action? You can add any of the gesture recognizers to UIImageView.

A simple example:
Code Block
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let tapGR = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped))
imageView.addGestureRecognizer(tapGR)
imageView.isUserInteractionEnabled = true
}
@objc func imageTapped(sender: UITapGestureRecognizer) {
if sender.state == .ended {
print("UIImageView tapped")
}
}
}


Accepted Answer
What sort of action? You can add any of the gesture recognizers to UIImageView.

A simple example:
Code Block
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let tapGR = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped))
imageView.addGestureRecognizer(tapGR)
imageView.isUserInteractionEnabled = true
}
@objc func imageTapped(sender: UITapGestureRecognizer) {
if sender.state == .ended {
print("UIImageView tapped")
}
}
}


Thank you!
Add action to an UIImageView?
 
 
Q