-
Book Overview & Buying
-
Table Of Contents
SwiftUI Cookbook
By :
In this section, we will display a list of countries and use a swipe motion to delete items from the list one at a time.
Let's start by creating a SwiftUI app called DeleteRowFromList.
We use the List view's .onDelete(perform: …) modifier to implement list deletion. The process is as follows:
ContentView struct called countries. The variable should contain an array of countries:@State var countries = ["USA", "Canada", "England","Cameroon", "South Africa", "Mexico" , "Japan", "South Korea"]
List view in the ContentView body that uses a ForEach loop to display the contents of the countries array: List {
ForEach(countries, id: \.self) { country in
Text(country)
}
}.onDelete(perform: self.deleteItem) modifier to the ForEach loop.deleteItem() function. The function should be placed below the body variable's closing brace: private func deleteItem(at indexSet: IndexSet){
self.countries.remove(atOffsets: indexSet)
}List view in a navigation view and add a .navigationBarTitle("Countries", displayMode: .inline) modifier to the list. The resulting ContentView struct should be as follows:struct ContentView: View {
@State var countries = ["USA", "Canada", "England","Cameroon", "South Africa", "Mexico" , "Japan", "South Korea"]
var body: some View {
NavigationView{
List {
ForEach(countries, id: \.self) { country in
Text(country)
}
.onDelete(perform: self.deleteItem)
}
.navigationBarTitle("Countries", displayMode: .inline)
}
}
private func deleteItem(at indexSet: IndexSet){
self.countries.remove(atOffsets: indexSet)
}Run the canvas review by clicking the play button next to the canvas preview. A swipe from right to left on a row causes a Delete button to appear. Click on the button to delete the row:
Figure 2.6 – DeleteRowFromList preview execution
Run the app live preview and admire the work of your own hands!
Navigation views and list views were discussed earlier. Only the .onDelete(…) modifier is new. The .onDelete(perform: self.deleteItem) modifier triggers the deleteItem() function when the user swipes from right to left.
The deleteItem(at indexSet: IndexSet) function takes a single parameter, IndexSet, which represents the index of the row to be removed/deleted. The .onDelete() modifier automatically knows to pass the IndexSet parameter to deleteItem(…).
Deleting an item from a list view can also be performed by embedding the list in a navigation view and adding an EditButton component.