无法在UITapGestureRecognizer中传递UIImageView

时间:2016-10-27 11:07:45

标签: ios swift uitapgesturerecognizer

我正在尝试通过UIImageViewUITapGestureRecognizer作为参数传递给我,例如addTapGestureRecognizer(passedView: questionImage)其中questionImageUIImageView。代码如下:

    // 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并打印第二个语句。我在这里做错了什么?

2 个答案:

答案 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")
    }