我正在尝试在 SwiftUI 中创建一个动态分组列表,我想知道如何实现 onDelete
在这种情况下。从我读到的this method它采取接收 IndexSet 的操作.当您只有一个 ForEach(无分组)时,这一切都很好,但是当您添加嵌套的 ForEach(已实现的分组)时,实现项目功能的“滑动删除”功能中断。问题是我不确定 onDelete
是否应该在外面ForEach
或内部的,两者都不起作用,因为无法从中检测到 Category
items
中的对象通过了IndexSet
这样我就可以执行项目的删除。有什么想法吗?这是我的模型和 View :
型号:
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 products = [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.products) { product in
Text(product.name)
}
.onDelete(perform: self.removeItems)
}
}
}
.listStyle(GroupedListStyle())
}
func removeItems(at offsets: IndexSet) {
// This does not work correctly with nested ForEach
// How to correctly remove the swiped element from the `.products`
// Not sure how to find the correct `Category` which element was swiped.
offsets.forEach{ offset in
print(offset) // prints 0, 1 etc.
}
}
}
最佳答案
只需将类别传递给您的 removeItems 函数
.onDelete(perform: { offsets in
self.removeItems(at offsets: offsets, from category: category)
})
func removeItems(at offsets: IndexSet, from category: Category) {
// You now know which category to delete from and at which index
}
关于ios - SwiftUI:如何 "swipe delete"嵌套 ForEach 中的元素(分组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58872202/