在 SwiftUI 中更新树结构的 UI

Updating the UI for a tree structure in SwiftUI

我有一个 ObservableObject class,Model0 有一个 Published 对象 nestednested 对象表示递归树结构。我希望能够更新树结构并适当更新 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)
        }
    }
}

如果您决定制作 reference-type 模型,那么您需要使所有模型都可观察,这样每个级别都可以更新相应的视图。当然,每个关卡模型都有单独的视图。

考虑到以上情况,这里有一个解决方案。测试 Xcode 12 / iOS 14.

仅修改部分:

class Nested: ObservableObject, Identifiable {
    var id: UUID = UUID()
    @Published var name: String
    @Published var children:[Nested]

    init(name: String, children:[Nested]) {
        self.children = children
        self.name = name
    }
}

struct NestedView: View {
    @ObservedObject var nested: Nested

    var body: some View {
        VStack {
            Text(nested.name)

            ForEach(nested.children) { c in
                NestedView(nested: c)
            }
        }
    }
}