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)")
}
}
}
``
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
}
backup
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With