UITapGestureRecognizer 没有附加动作

UITapGestureRecognizer not attaching action

我为 View 创建了一个单独的 class。 我把所有的功能都留在了控制器中。 但是当我在图片上添加点击时,不知为何不起作用

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 将是一个静态函数,不可用。

您可以改用委托。

委托协议和视图。

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()
    }
}

ViewController:

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

这将不起作用,因为您是在没有任何 class 引用或对象的情况下直接调用 UIViewController 方法。解决方案是使用协议或 clouser 从视图到 class.

获取操作

class

class APOTDView: UIView {
    @objc var imageViewAction: ((UITapGestureRecognizer) -> Void)? = nil
    
    lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.backgroundColor = .blue
        imageView.translatesAutoresizingMaskIntoConstraints = true
        imageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector((imageTapped(_:))))
        imageView.addGestureRecognizer(tap)
        return imageView
    }()
    
    @objc private func imageTapped(_ sender: UITapGestureRecognizer) {
        self.imageViewAction?(sender)
    }
}

ViewController

class APOTDViewController: UIViewController {
    let av = APOTDView()

    override func viewDidLoad() {
        super.viewDidLoad()
        av.imageViewAction = { sender in
            print("good job")
        }
    }
}