-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

SwiftUI Cookbook
By :

So far, we've learned how to add new rows to a list. Now, let's find out how to use a swipe motion to delete items one at a time.
Create a new SwiftUI app called ListRowDelete
.
We will create a list of items and use the list view's onDelete
modifier to delete rows. The steps are as follows:
state
variable to the ContentView
struct called countries
and initialize it with an array of country names:@State var countries = ["USA", "Canada", "England", "Cameroon", "South Africa", "Mexico" , "Japan", "South Korea"]
navigationView
and a List
view that displays our array of countries. Also, include the onDelete
modifier at the end of the ForEach
structure:NavigationView{ List { ForEach(countries, id: \.self) { country in Text(country) } .onDelete(perform: self.deleteItem) } .navigationBarTitle("Countries", displayMode: .inline) }
deleteItem
function:private func deleteItem(at indexSet: IndexSet){ self.countries.remove(atOffsets: indexSet) }
The resulting preview should look as follows:
Figure 2.6 – ListRowDelete in action
Run the canvas preview and swipe right to left on a list row. The Delete button will appear and can be clicked to delete an item from the list.
In this recipe, we introduced the .onDelete
modifier, whose perform
parameter takes a function that will be executed when clicked. In this case, deleting an item triggers the execution of our deleteItem
function.
The deleteItem
function takes a single parameter, IndexSet
, which is the index of the row to be deleted. The onDelete
modifier automatically passes the index of the item to be deleted.
Deleting an item from a List
view can also be performed by embedding the list navigation view and adding an EditButton
component.