SwiftUI: the List view
By Flavio Copes
Learn how to use the List view in SwiftUI to show data in rows, group items with Section, fill rows with ForEach, and change the look with listStyle.
The List view is one of the most useful views you’ll use in SwiftUI.
List {
}
Inside it, you can put a series of views, like Text for example:

See? List recognizes the Text child view, and puts it inside a row.
You can put more than one, and each child of List will be put on its own row:

Inside a list, you can group items using the Section view:
List {
Section("First 2") {
Text("One")
Text("Two")
}
Section("Others") {
Text("Three")
}
}

Hard-coded rows are fine for small lists. For an array, put a ForEach inside the List. If your type conforms to Identifiable, you can skip the id parameter:
struct Fruit: Identifiable {
let id = UUID()
let name: String
}
let fruits = [
Fruit(name: "Apple"),
Fruit(name: "Pear"),
Fruit(name: "Orange")
]
List {
ForEach(fruits) { fruit in
Text(fruit.name)
}
}
I cover ranges, id: \.self, and more in the ForEach post.
You can put a NavigationLink in a row when the list sits inside a navigation stack. Tapping the row pushes the destination:
NavigationStack {
List {
NavigationLink("Apple") {
Text("Apple details")
}
}
}
An empty List draws nothing until you add rows. That is normal. Put a placeholder Text in the list when you want the user to see that there is no data yet.
The listStyle() modifier of List can let you customize the List appearance. Pass a style value such as:
.insetGrouped.inset.sidebar.grouped.plain
For example here’s .insetGrouped:
List {
//...
}.listStyle(.insetGrouped)

And here’s .grouped:
List {
//...
}.listStyle(.grouped)

Here’s .sidebar:

Want me to talk about your product? You can sponsor this site.
Related posts about swift: