Reputation: 3977
I'm trying to pass a UIImageView
as a parameter through a UITapGestureRecognizer
, e.g. addTapGestureRecognizer(passedView: questionImage)
where questionImage
is a UIImageView
. Code like so:
// MARK: Tap Gesture Recognizer
func addTapGestureRecognizer(passedView: UIView) {
let photoTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapPhoto(_:)))
photoTapGestureRecognizer.numberOfTapsRequired = 1
passedView.isUserInteractionEnabled = true
passedView.addGestureRecognizer(photoTapGestureRecognizer)
}
func didTapPhoto(_ sender: UITapGestureRecognizer) {
print("Did detect the tap")
if let imageView = sender as? UIImageView {
print("Is an image view")
}
}
When I tap the UIImageView
it detects the tap and prints the first statement. However it will not cast sender
into a UIImageView
and print the second statement. What am I doing wrong here?
Upvotes: 0
Views: 103
Reputation: 1037
if let imageView = sender.view as? UIImageView {
print("Is an image view")
}
Upvotes: 0
Reputation: 11127
You need to pass sender.view
in order to get which view is tapped
func didTapPhoto(_ sender: UITapGestureRecognizer) {
print("Did detect the tap")
if (sender.view as? UIImageView) != nil {
print("Is an image view")
}
}
Upvotes: 2