6
  1. 创建一个简单的 ARClass: ObservableObject with @Published var name: String
  2. 创建自定义 ARView:UIView 接收 ARClass 作为参数并在中心从 ARClass.name 绘制文本
  3. 创建 UIViewRepresentable

然后通过使用 ARClass(color: .red, name: "Test Text") 作为 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 之外,整个主体都被刷新了,它总是将“名称”变量重置为其初始值。

4

1 回答 1

7

几个小时后,我终于知道 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()
    }
}
于 2019-09-28T04:53:25.343 回答