我正在尝试通过UIImageView
将UITapGestureRecognizer
作为参数传递给我,例如addTapGestureRecognizer(passedView: questionImage)
其中questionImage
是UIImageView
。代码如下:
// 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")
}
}
当我点击UIImageView
时,它会检测到水龙头并打印第一个语句。但是,它不会将sender
转换为UIImageView
并打印第二个语句。我在这里做错了什么?
答案 0 :(得分:2)
您需要传递sender.view
才能获得点击的视图
func didTapPhoto(_ sender: UITapGestureRecognizer) {
print("Did detect the tap")
if (sender.view as? UIImageView) != nil {
print("Is an image view")
}
}
答案 1 :(得分:0)
if let imageView = sender.view as? UIImageView {
print("Is an image view")
}