【问题标题】:How to perform onDelete with Section item inside ForEach in SwiftUI如何在 SwiftUI 中的 ForEach 中使用 Section 项执行 onDelete
【发布时间】:2021-02-15 20:11:56
【问题描述】:

在绝对新的项目中,我有这段代码用于测试:

extension Int: Identifiable {
    
    public var id: UUID { UUID() }
}

struct ContentView: View {
    
    let data: [Int] = [1, 2, 3, 4, 5]
    
    var body: some View {
        List {
            ForEach(data) {
                Section(header: Text("\($0)")) {
                    ForEach(data) {
                        Text("\($0)")
                    }.onDelete(perform: { indexSet in
                        print("Delete \(indexSet)")
                    })
                }
            }
        }
    }
}

在这种情况下,没有滑动删除之类的操作。默认情况下,您可以在对 ForEach 键入 onDelete 后立即滑动并查看删除按钮。但是,当您将 Section 放在 ForEach 中时,这并没有发生。 当我删除部分时它会出现。即使我在 ForEach 中的 ForEach 中有 ForEach 它仍然有效。但里面没有 Section - 为什么?

Xcode 12.4 斯威夫特 5

【问题讨论】:

    标签: ios swift swiftui swiftui-list


    【解决方案1】:

    您只需要提供一个数组数组,其中包含每个部分的行:

    struct ContentView: View {
        @State var data: [[Int]] = [[1, 2, 3, 4, 5],[1, 2, 3, 4, 5],[1, 2, 3, 4, 5],[1, 2, 3, 4, 5],[1, 2, 3, 4, 5]]
        var body: some View {
            List {
                ForEach(data.indices, id: \.self) { section in
                    Section(header: Text("\(section+1)")) {
                        ForEach(data[section], id: \.self) { row in
                            Text("\(row)")
                        }.onDelete(perform: { indexSet in
                            data[section].remove(atOffsets: indexSet)
                        })
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      相关资源
      最近更新 更多