SwiftUI:如何“滑动删除”嵌套 ForEach 中的元素(分组)

Vla*_*kov 3 ios swift swiftui

我正在尝试在 SwiftUI 中创建一个动态分组列表,我想知道如何onDelete在这种情况下实现一个。从我读到的关于这个方法的内容来看,它采取了一个接收IndexSet的动作。当您只有一个 ForEach(无分组)时,这一切都很好,但是当您添加嵌套的 ForEach(实施分组)以实现“滑动删除”项目功能时,这一切都很好。问题是我不确定onDelete应该放在外部ForEach还是内部,两者都不起作用,因为无法检测传递中的哪个Category对象,因此我可以执行删除项目。有什么想法吗?这是我的模型和视图:itemsIndexSet

模型:

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]()
}
Run Code Online (Sandbox Code Playgroud)

并查看:

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

}
Run Code Online (Sandbox Code Playgroud)

LuL*_*aGa 5

只需将类别传递给您的 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
}
Run Code Online (Sandbox Code Playgroud)