gpt4 book ai didi

ios - SwiftUI:更改 "Dynamic List with groups"属性时 `@Published` 未刷新

转载 作者:行者123 更新时间:2023-11-28 13:23:02 26 4
gpt4 key购买 nike

我正在尝试在 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]()
}

和 View

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)
}
}
}

当我附加到 Category (existingCategory?.items.append(product)) 的项目时,UI 不会更新,除非我进入不同的 View 使用导航或使用 .sheet()

有人知道这里出了什么问题吗?我对 Swift 和 SwfitUI 还很陌生。

最佳答案

您的 View 仅观察categories,因此只有直接更改categories 才会导致重绘您的 View 。

这就是为什么 self.categories.items.append(Category()) 总是会导致 View 重绘,但是 existingCategory?.items.append(product) 是不是。

existingCategory?.items.append(product) 只是将一个元素添加到 categories 类别元素之一,但类别元素仍然相同,因此没有更改位置直接对观察到的类别进行制作。

你可以试试这个:

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

这也总是会导致重绘您的 View ,因为您直接在 categories 绑定(bind)上操作。

关于ios - SwiftUI:更改 "Dynamic List with groups"属性时 `@Published` 未刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58817625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com