Deleting rows from a list
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.
Getting ready
Create a new SwiftUI app called ListRowDelete
.
How to do it…
We will create a list of items and use the list view’s onDelete
modifier to delete rows. The steps are as follows:
- Add a
state
variable to theContentView
struct calledcountries
and initialize it with an array of country names:@State private var countries = ["USA", "Canada", "Mexico", "England", "Spain", "Cameroon", "South Africa", "Japan", "South Korea"]
- Replace the content of the body variable with a
NavigationStack
containing aList
view that displays our array of countries. Also, include theonDelete
modifier at the end of theForEach
structure:NavigationStack { ...