With a List
one can simply use the .onDelete
modifier to remove the rows from the List. But how can we do the same in a ForEach
shown within a LazyVStack
. I am using SwipeCell to apply a drag gesture and showing a delete button but how do I actually remove from CoreData, specifically how do I access the IndexSet
in this case
LazyVStack {
ForEach(items) { item in
Text("\(item.name)")
.swipeCell(cellPosition: .right, leftSlot: nil, rightSlot: slot1)
.alert(isPresented: $showAlert){
Alert(title: Text("Delete Task?"), message: nil, primaryButton:.destructive(Text("Delete"), action: {
// HOW DO I DELETE HERE ?
dismissDestructiveDelayButton()
}),secondaryButton: .cancel({dismissDestructiveDelayButton()}))
}
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { items[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}