我有一个 ObservableObject 类,Model0
它有一个Published
object nested
。该nested
对象表示递归树结构。我希望能够更新树结构并适当地更新 UI。但是,在下面的代码中,当我更新对象的子nested
对象时,UI 没有更新,我假设是因为对的引用nested
没有改变。nested
每当我更改树结构中的任何对象时,如何让 UI 更新?
class Nested: Identifiable {
var id: UUID = UUID()
var name: String
var children:[Nested]
init(name: String, children:[Nested]) {
self.children = children
self.name = name
}
}
class Model0 : ObservableObject {
@Published var nested: Nested
init(nested: Nested) {
self.nested = nested
}
func update() {
nested.children[0] = Nested(name:"New", children: [])
}
}
struct NestedView: View {
var nested: Nested
var body: some View {
VStack {
Text(nested.name)
ForEach(nested.children) { c in
NestedView(nested: c)
}
}
}
}
struct Test: View {
@ObservedObject var model: Model0 = Model0(nested: Nested(name: "Parent" ,children: [Nested(name: "Child", children: [])]))
var body: some View {
VStack {
Button(action: {
self.model.update()
}) {
Text("Update")
}
NestedView(nested: model.nested)
}
}
}