如何在包含动态分区的SwiftUI列表中删除一个项目?

4

假设我有一个SwiftUI视图,显示按部门分组的员工列表,如何删除部门中的项目? 与UITableView中的向左滑动删除行为相同。

import SwiftUI

struct ContentView: View {
    var data: [String : [String]] = ["DeptA": ["EmpA", "EmpB", "EmpC"], "DeptB": ["EmpD", "EmpE", "EmpF"]]

    var body: some View {
        NavigationView {

            List {
                ForEach(data.keys.map { String($0) }, id: \.self) { dept in
                    Section(header: Text(dept)) {
                        ForEach(self.data[dept]!, id: \.self) { emp in
                            Text(emp)
                        }.onDelete(perform: self.deleteEmp)
                    }
                }
            }
            .navigationBarTitle("Employees")
        }
    }

    private func deleteEmp(indexSet: IndexSet) {
        print(indexSet.first!)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

2
您可以使用闭包来为 .onDelete 创建一个函数,其中您将要删除的索引集合以及部门或其他标识信息一起传递给 self.deleteEmp - Fabian
终于有一个可行的解决方案了,我感觉自己好蠢。谢谢。 - M.Serag
1
当你传递一个方法本身(而不是调用它)时,你总是可以传递一个闭包。它只是并不经常发生,所以并不明显同意。 - Fabian
1个回答

7
从数据源中移除它:
struct ContentView: View {
    @State var dataSource = ["1", "2", "3", "4"]

    var body: some View {

        List(dataSource, id: \.self) { number in

            Text("Click Here to delete this row " + number)
                .onTapGesture {
                    let index = self.dataSource.firstIndex(of: number)!
                    self.dataSource.remove(at: index)
            }
        }
    }
}

更新您的代码

您将数据源嵌套在两个ForEach中。第一个可以访问section,第二个可以访问row。所以:

struct ContentView: View {
    var data: [String : [String]] = ["DeptA": ["EmpA", "EmpB", "EmpC"],
                                     "DeptB": ["EmpD", "EmpE", "EmpF"]]
    var sections: [String] { data.keys.map { $0 } }
    func rows(section: Int) -> [String] { data[sections[section]]! }

    var body: some View {
        NavigationView {

            List {
                ForEach(0..<sections.count, id: \.self) { section in
                    Section(header: Text(self.sections[section])) {
                        ForEach(self.rows(section: section), id: \.self) { emp in
                            Text(emp)
                        }.onDelete { row in
                            self.deleteEmp(section: section, row: row)
                        }
                    }
                }
            }.navigationBarTitle("Employees")
        }
    }

    private func deleteEmp(section: Int, row: IndexSet) {
        print("Section:", section)
        print("Row:", row.first!)
    }
}

请注意,我使用了一些辅助变量和函数。

该列表包含若干个部分,每个部分包含需要删除的单元格。我使用了onDelete修饰符,但是它为每个部分提供相同的索引集合,因此我不知道它是哪个部分。 - M.Serag
发一下代码,我来看看。做完了告诉我。 - Mojtaba Hosseini
你将数据源嵌套在两个 ForEach 中。第一个可以访问 section,第二个可以访问 row。请使用它们。 - Mojtaba Hosseini
好的 @MojtabaHosseini 谢谢 - Kiran Thapa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接