- 创建一个简单的 ARClass: ObservableObject with @Published var name: String
- 创建自定义 ARView:UIView 接收 ARClass 作为参数并在中心从 ARClass.name 绘制文本
- 创建 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 之外,整个主体都被刷新了,它总是将“名称”变量重置为其初始值。