SwiftUI不使用UIViewRepresentable和ObservableObject刷新我的自定义UIView

时间:2019-09-28 02:40:01

标签: swiftui uiviewrepresentable

  1. 使用@Published var创建一个简单的ARClass:ObservableObject 名称:字符串
  2. 创建自定义ARView:UIView收到的ARClass为 参数并从中心的ARClass.name绘制文本
  3. 创建UIViewRepresentable

,然后通过将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'变量重置为其初始值。

1 个答案:

答案 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()
    }
}