SwiftUI:当更改@Published属性时,“带有组的动态列表”未刷新

时间:2019-11-12 11:20:40

标签: ios swift list swiftui

我正在尝试在SwiftUI中创建一个 动态分组列表 ,并且遇到一个问题,如果我更改内部ForEach标记为@Published的集合除非我转到其他屏幕/工作表,否则该更改在UI中不可见。我不知道我在做什么是正确的还是不正确的错误,关于“ SwiftUI中的动态分组列表”的资源非常有限,所以我希望您指出正确的方向。

这是我的设置:

型号:

class Product: Identifiable, ObservableObject {
    let id = UUID()
    var name: String

    init(name: String) {
        self.name = name
    }
}

class Category: Identifiable, ObservableObject {
    let id = UUID()
    @Published var items = [Product]()
    var categoryName = ""
}

class Categories: ObservableObject {
    @Published var items = [Category]()
}

和视图

struct ProductListView: View {
    @ObservedObject var categories: Categories = Categories()


    var body: some View {
            List {
                ForEach(categories.items) { category in
                    Section(header: Text(category.categoryName)) {
                        ForEach(category.items) { item in
                            Text(item.name)
                        }
                    }
                }
            }
            .listStyle(GroupedListStyle())
    }

    func appendProduct() {
        let product = Product(name: self.$name.wrappedValue, quantity: 1, complated: false)
        let basicCategory = "Generic"
        let existingCategory = self.categories.items.filter({$0.categoryName == basicCategory}).first
        if (existingCategory?.items != nil) {

            // Changes here do not refresh the UI 
            existingCategory?.items.append(product)
        } else {
            let category = Category()
            category.categoryName = basicCategory
            category.items.append(product)
            self.categories.items.append(category)
        }
    }
}

当我追加到CategoryexistingCategory?.items.append(product))的项目时,除非更新了导航或使用.sheet()的视图,否则UI不会更新。

任何人都知道这里有什么问题吗?我对Swift和SwfitUI还是很陌生。

1 个答案:

答案 0 :(得分:1)

您的视图仅观察categories,因此仅直接更改categories会导致视图重画。

这就是self.categories.items.append(Category())总是会导致视图重绘而existingCategory?.items.append(product)却不会导致视图重绘的原因。

existingCategory?.items.append(product)只是将一个元素添加到categories类别元素之一中,但是类别元素仍然是相同的,因此在直接对观察到的categories进行更改的地方没有任何改变。

您可以尝试以下方法:

self.$categories.items[0].items.wrappedValue.append(product)

这也总是会导致您重新绘制视图,因为您直接在categories绑定上进行操作。