[SOLVED] How to add confirmation to .ondelete() of List in SwiftUI

Issue

How can I add a confirmation to my deleteRow() function?
A already added the .alert but I don’t know how to continue.

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)")
        }
    }
}
``

Solution

Here is possible approach:

@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
}

Answered By – Asperi

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.