在UITapGestureRecognizer中传递UIImag

在UITapGestureRecognizer中传递UIImag

我试图把aUIImageView作为一个参数通过aUITapGestureRecognizer,例如addTapGestureRecognizer(passedView: questionImage),其中questionImage是aUIImageView。这样的代码:

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

最佳答案

你需要通过sender.view才能得到哪个视图被点击

func didTapPhoto(_ sender: UITapGestureRecognizer) {
    print("Did detect the tap")
    if (sender.view as? UIImageView) != nil {
        print("Is an image view")
    }

}

关于ios - 无法在UITapGestureRecognizer中传递UIImageView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40283069/

10-09 16:34