UITapGestureRecognizer 没有附加动作 [英] UITapGestureRecognizer not attaching action

查看:27
本文介绍了UITapGestureRecognizer 没有附加动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为 View 创建了一个单独的类.我把所有的功能都留在了控制器中.但是当我在图片上添加一个点击时,它由于某种原因不起作用.

I created a separate class for View. I left all the functions in the Controller. But when I add a click on the picture, it doesn't work for some reason.

import UIKit

class APOTDView: UIView {

    var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(APOTDViewController.imageTapped(_:)))
        imageView.addGestureRecognizer(tap)

        return imageView
    }()
}

import UIKit

class APOTDViewController: UIViewController {

    let av = APOTDView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // ... add subview and constraint
    }

    @objc func imageTapped(_ sender: UITapGestureRecognizer) {
        print("good job")
    }
}

怎么了?请帮我弄清楚

推荐答案

您在 UITapGestureRecognizer 中的选择器是错误的.不能直接调用APOTDViewController.
APOTDViewController.imageTapped 将是一个静态函数,该函数不可用.

Your selector in the UITapGestureRecognizer is wrong. You can not call the APOTDViewController directly.
APOTDViewController.imageTapped would be a static function, which is not available.

您可以改用委托.

委托协议和视图.

protocol APOTDViewDelegate: AnyObject {
    func viewDidTapImage()
}

class APOTDView: UIView {
    weak var delegate: APOTDViewDelegate?

    var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
        imageView.addGestureRecognizer(tap)

        return imageView
    }()

    @objc func imageTapped() {
        delegate?.viewDidTapImage()
    }
}

视图控制器:

class APOTDViewController: UIViewController, APOTDViewDelegate {
    let av = APOTDView()

    override func viewDidLoad() {
        super.viewDidLoad()
        av.delegate = self
        // ... add subview and constraint
    }

    @objc func viewDidTapImage() {
        print("good job")
    }
}

这篇关于UITapGestureRecognizer 没有附加动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆