[英]SwiftUI: "Dynamic List with groups" not refreshed when an `@Published` property is changed
我正在嘗試在 SwiftUI 中創建一個動態分組列表,但我面臨一個問題,如果我更改標記為內部 ForEach 的 @Published 的集合,則該更改在 UI 中不可見,除非我 go 到不同的屏幕/工作表. 我不明白我在做什么是正確的還是不正確的錯誤,關於“SwiftUI 中的動態分組列表”主題的資源非常有限,所以我希望你能指出我正確的方向。
這是我的設置:
Model:
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)
}
}
}
當我 append 到Category
( existingCategory?.items.append(product)
) 的項目時,UI 不會更新,除非我通過導航或使用.sheet()
到達不同的視圖
任何人都知道這里出了什么問題? 我對 Swift 和 SwfitUI 很陌生。
您的 View 只是觀察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
綁定上進行操作。
在Swift中,Category和Product應該是一個struct。
這為您提供了值語義,這是 SwiftUI 用來檢測更改的內容。 即,對產品的更改被檢測為對類別的更改,這被檢測為對 SwiftUI 正在觀察的@Published
項目的更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.