斯威夫特 5.0 iOS 13
尝试了解 UIViewRepresentable 的工作原理,并将这个简单的示例放在一起,几乎就这样了,但也许完全是无稽之谈。是的,我知道 SwiftUI 中已经有一个 tapGesture,这只是一个测试。
无法编译,因为它说在从初始化程序返回之前不会在所有路径上调用“super.init”,我尝试并设置了它,但显然不正确。
import SwiftUI
struct newView: UIViewRepresentable {
typealias UIViewType = UIView
var v = UIView()
func updateUIView(_ uiView: UIView, context: Context) {
v.backgroundColor = UIColor.yellow
}
func makeUIView(context: Context) -> UIView {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(Coordinator.handleTap(sender:)))
v.addGestureRecognizer(tapGesture)
return v
}
func makeCoordinator() -> newView.Coordinator {
Coordinator(v)
}
final class Coordinator: UIView {
private let view: UIView
init(_ view: UIView) {
self.view = view
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func handleTap(sender: UITapGestureRecognizer) {
print("tap")
}
}
}
只需让你的Coordinator
is a NSObject
,它通常扮演桥梁/控制器/委托/演员角色,但不扮演演示角色,所以不应该is-a-UIView
final class Coordinator: NSObject {
private let view: UIView
init(_ view: UIView) {
self.view = view
}
还有一个...
func makeUIView(context: Context) -> UIView {
// make target a coordinator, which is already present in context !!
let tapGesture = UITapGestureRecognizer(target: context.coordinator,
action: #selector(Coordinator.handleTap(sender:)))
v.addGestureRecognizer(tapGesture)
return v
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)