ios - SwiftUI:如何 "swipe delete"嵌套 ForEach 中的元素(分组)

标签 ios swift swiftui

我正在尝试在 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/

相关文章:

ios - 为什么我的 Swift for-in-loop 不执行/迭代?

swift - 如何做某事(例如 : print ("hi")) in NavigationLink before moving to a destinationView

swift - 登录屏幕 SwiftUI

ios - SpriteKit 中的定时定时器

ios - 使用 sortedArrayUsingSelector : with non-letter characters at the end?

ios - iOS 8 和 iOS 9 上 NSURLSession 的区别?

ios - 以编程方式创建 UITableViewCells

ios - UIScrollerView 内的 UIView 以 -64 偏移量显示

ios - Swift - 每个 View 中的响应 View ?

ios - SwiftUI - 如何避免在修改来自同一结构的状态变量时刷新列表