如何在SwiftUI中从列表中删除多行?

时间:2019-11-18 07:47:43

标签: list swiftui delete-row

我从这个问题中举了一个例子:How does one enable selections in SwiftUI's List,并编辑了代码以能够删除一行。但是我不知道如何从列表中删除多行。

可以帮我吗?

var demoData = ["Phil Swanson", "Karen Gibbons", "Grant Kilman", "Wanda Green"]

struct ContentView : View {
    @State var selectKeeper = Set<String>()

    var body: some View {
        NavigationView {
            List(selection: $selectKeeper){
                ForEach(demoData, id: \.self) { name in
                    Text(name)
                }
                .onDelete(perform: delete)
            }
            .navigationBarItems(trailing: EditButton())
            .navigationBarTitle(Text("Selection Demo \(selectKeeper.count)"))
        }
    }

    func delete(at offsets: IndexSet) {
        demoData.remove(atOffsets: offsets)
    }
}

1 个答案:

答案 0 :(得分:0)

SwiftUI how to perform action when EditMode changes?的解决方案

 struct Item: Identifiable {
    let id = UUID()
    let title: String

    static var i = 0
    init() {
        self.title = "\(Item.i)"
        Item.i += 1
    }
}

struct ContentView: View {
    @State var editMode: EditMode = .inactive
    @State var selection = Set<UUID>()
    @State var items = [Item(), Item(), Item()]

    var body: some View {
        NavigationView {
            List(selection: $selection) {
                ForEach(items) { item in
                    Text(item.title)
                }
            }
            .navigationBarTitle(Text("Demo"))
            .navigationBarItems(
                leading: editButton,
                trailing: addDelButton
            )
            .environment(\.editMode, self.$editMode)
        }
    }

    private var editButton: some View {
        Button(action: {
            self.editMode.toggle()
            self.selection = Set<UUID>()
        }) {
            Text(self.editMode.title)
        }
    }

    private var addDelButton: some View {
        if editMode == .inactive {
            return Button(action: addItem) {
                Image(systemName: "plus")
            }
        } else {
            return Button(action: deleteItems) {
                Image(systemName: "trash")
            }
        }
    }

    private func addItem() {
        items.append(Item())
    }

    private func deleteItems() {
        for id in selection {
            if let index = items.lastIndex(where: { $0.id == id }) {
                items.remove(at: index)
            }
        }
        selection = Set<UUID>()
    }
}

extension EditMode {
    var title: String {
        self == .active ? "Done" : "Edit"
    }

    mutating func toggle() {
        self = self == .active ? .inactive : .active
    }
}