< Sorting fetch requests with NSSortDescriptor | Using an alert to pop a NavigationLink programmatically > |
We already used @FetchRequest
to place Core Data objects into a SwiftUI List
, and with only a little more work we can enable both swipe to delete and a dedicated Edit/Done button.
Just as with regular arrays of data, most of the work is done by attaching an onDelete(perform:)
modifier to ForEach
, but rather than just removing items from an array we instead need to find the requested object in our fetch request then use it to call delete()
on our managed object context. Once all the objects are deleted we can trigger another save of the context; without that the changes won’t actually be written out to disk.
So, start by adding this method to ContentView
:
func deleteBooks(at offsets: IndexSet) {
for offset in offsets {
// find this book in our fetch request
let book = books[offset]
// delete it from the context
moc.delete(book)
}
// save the context
try? moc.save()
}
We can trigger that by adding an onDelete(perform:)
modifier to the ForEach
of ContentView
, but remember: it needs to go on the ForEach
and not the List
.
Add this modifier now:
.onDelete(perform: deleteBooks)
That gets us swipe to delete, and we can go one better by adding an Edit/Done button too. Find the navigationBarItems()
modifier in ContentView
, and change its first line to this:
.navigationBarItems(leading: EditButton(), trailing: Button(action: {
That completes ContentView
, so try running the app – you should be able to add and delete books freely now, and can delete by using swipe to delete or using the edit button.
SPONSORED ViRE offers discoverable way of working with regex. It provides really readable regex experience, code complete & cheat sheet, unit tests, powerful replace system, step-by-step search & replace, regex visual scheme, regex history & playground. ViRE is available on Mac & iPad.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.