如何在SwiftUI中向列表的.ondelete()添加确认

时间:2020-07-03 18:01:27

标签: ios swift listview swiftui

如何为我的deleteRow()函数添加确认? 已经添加了.alert,但我不知道如何继续。

List {
    ForEach(data, id: \.self) { item in
        Text(item)
        .alert(isPresented: self.$showingDeleteAlert) {
            Alert(title: Text("..."), message: Text("..."), primaryButton: .destructive(Text("Delete")) {
                deleteRow // ???
                }, secondaryButton: .cancel()
            )
        }
    }
    .onDelete(perform: deleteRow)
}

func deleteRow(at indexSet: IndexSet) {
    for index in indexSet {
        let item = data[index]
        viewContext.delete(item)
        do {
            try viewContext.save()
        } catch let error {
            print("Error: \(error)")
        }
    }
}
``

1 个答案:

答案 0 :(得分:0)

这是可能的方法(抓痒)

@State private var toBeDeleted: IndexSet?

...

List {
    ForEach(data, id: \.self) { item in
        Text(item)
        .alert(isPresented: self.$showingDeleteAlert) {
            Alert(title: Text("..."), message: Text("..."), primaryButton: .destructive(Text("Delete")) {
                    for index in self.toBeDeleted {
                        let item = data[index]
                        viewContext.delete(item)
                        do {
                            try viewContext.save()
                        } catch let error {
                            print("Error: \(error)")
                        }
                    }
                    self.toBeDeleted = nil
                }, secondaryButton: .cancel() {
                    self.toBeDeleted = nil
                }
            )
        }
    }
    .onDelete(perform: deleteRow)
}

func deleteRow(at indexSet: IndexSet) {
    self.toBeDeleted = indexSet           // store rows for delete
    self.showingDeleteAlert = true
}