如何删除swiftui列表中包含动态部分的项目?

时间:2019-09-01 18:33:54

标签: swift swiftui

比方说,我有一个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()
    }
}

1 个答案:

答案 0 :(得分:1)

从数据源中删除它:

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中。第一个可以访问节,第二个可以访问行。所以:

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!)
    }
}

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