5

我有一个 ObservableObject 类,Model0它有一个Publishedobject 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)
        }
    }
}
4

1 回答 1

2

如果您决定制作引用型模型,那么您需要使它们都可观察,这样每个级别都可以更新相应的视图。当然,每个级别模型都有单独的视图。

考虑到上述情况,这里有一个解决方案。使用 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)
            }
        }
    }
}
于 2020-08-19T14:07:15.547 回答