如何解决UITapGestureRecognizer 没有附加动作
我为 View 创建了一个单独的类。 我把所有的功能都留在了控制器中。 但是当我在图片上添加一个点击时,它由于某种原因不起作用。
False
False
True
['__annotations__','__class__','__dataclass_fields__','__dataclass_params__','__delattr__','__dict__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__gt__','__hash__','__init__','__init_subclass__','__le__','__lt__','__module__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__','__weakref__']
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
}()
}
怎么了?请帮我弄清楚
解决方法
您在 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()
}
}
视图控制器:
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")
}
}
,
这行不通,因为您在没有任何类引用或对象的情况下直接调用 UIViewController
方法。解决方案是使用协议或clouser 来获取从视图到类的操作。
类
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)
}
}
视图控制器
class APOTDViewController: UIViewController {
let av = APOTDView()
override func viewDidLoad() {
super.viewDidLoad()
av.imageViewAction = { sender in
print("good job")
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。