,然后通过将ARClass(颜色:.red,名称:“测试文本”)用作SceneDelegate中的Environment对象,在SwuftUI View中使用
class ARClass: ObservableObject {
@Published var bg: UIColor
@Published var name: String
init(color: UIColor, name: String) {
self.bg = color
self.name = name
}
}
struct ARViewX: UIViewRepresentable {
var ar: ARClass
var frame: CGRect
func updateUIView(_ uiView: ARView, context: Context) {
uiView.frame = frame
uiView.ar = ar
uiView.setNeedsDisplay()
}
func makeUIView(context: Context) -> ARView {
ARView(ar: ar, frame: frame)
}
}
struct ContentView: View {
@EnvironmentObject var ar: ARClass
var body: some View {
GeometryReader { g in
VStack {
Spacer()
ARViewX(ar: self.ar, frame: CGRect(origin: .zero, size: .init(width: g.size.width, height: g.size.height/3)))
.padding()
Spacer()
Text(self.ar.name)
Divider()
TextField("Name", text: self.$ar.name)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
Spacer()
}
}
}
}
当我编辑TextField时,除了UIViewRepresentable之外,整个主体都会刷新,它总是将'name'变量重置为其初始值。
答案 0 :(得分:2)
几个小时后,我终于知道UIViewRepresentable中的updateUIView(_ uiView:ARView,context:Context)永远不会被调用,所以我像这样修改ARClass和UIViewRepresentable
class ARClass: ObservableObject {
@Published var bg: UIColor
@Published var name: String {
didSet {
if let onNameChange = onNameChange {
onNameChange()
}
}
}
var onNameChange: (()->Void)?
init(color: UIColor, name: String) {
self.bg = color
self.name = name
}
}
func updateUIView(_ uiView: ARView, context: Context) {
uiView.frame = frame
ar.onNameChange = {
uiView.setNeedsDisplay()
}
}