SwiftUI Blog

Mastering SwiftUI: Your Guide to Building Beautiful, Intuitive Apps.

List Actions


In the previous post, we saw how to create a List. In this one, we’ll learn how to perform actions on the list, primarily deletion. Before that, we need to introduce a new magic word: ForEach.
Take a look at the code below:

struct Vehicle: Identifiable {
    var id = UUID()
    var name: String
    var image: String
}

struct ContentView: View {
    var vehicles = [Vehicle(name: "car", image: "car"),
                    Vehicle(name: "bus", image: "bus"),
                    Vehicle(name: "tram", image: "tram"),
                    Vehicle(name: "bicycle", image: "bicycle")]
    
    var body: some View {
        ForEach(vehicles) { vehicle in
            RowView(vehicle: vehicle)
        }
    }
}
    
struct RowView: View {
    var vehicle: Vehicle
    var body: some View {
        HStack {
            Image(systemName: vehicle.image)
                .resizable()
                .frame(width: 60, height: 60)
            Text(vehicle.name)
        }
    }
}

To have:

As you can see, in this case, we only have a series of items, without scrolling or list styling. Here’s why:

ForEach is a view that creates an array of views.

List is a more complex view structure that generates rows within a scrollable view.

So, why do we need ForEach? It’s essential for performing actions, like deleting items, within a list. While List provides the appearance and functionality of a list, ForEach enables us to perform operations on the list’s data.

struct ContentView: View {
    @State var vehicles = [Vehicle(name: "car", image: "car"),
                    Vehicle(name: "bus", image: "bus"),
                    Vehicle(name: "tram", image: "tram"),
                    Vehicle(name: "bicycle", image: "bicycle")]
    
    var body: some View {
        List {
            ForEach(vehicles) { vehicle in
                RowView(vehicle: vehicle)
            }.onDelete { (indexSet) in
                self.vehicles.remove(atOffsets: indexSet)
            }
        }
    }
}

First, we added @State to the vehicles array because we need to modify it (e.g., removing an item).

Second, we included a ForEach within the List and attached the onDelete method to it.

In the onDelete, we remove the item at the selected indexSet.


By swiping left on a row, the delete button is displayed. Tapping it removes the row. That’s all!