SwiftUI: the List view

By

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:

Xcode showing SwiftUI List with single Text element and iPhone simulator displaying One in a list row

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:

Xcode showing SwiftUI List with three Text elements and iPhone simulator displaying One, Two, Three in separate rows

Inside a list, you can group items using the Section view:

List {
    Section("First 2") {
        Text("One")
        Text("Two")
    }
    Section("Others") {
        Text("Three")
    }
}

Xcode showing SwiftUI List with Section views and iPhone simulator displaying items grouped under FIRST 2 and OTHERS headers

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:

For example here’s .insetGrouped:

List {
		//...
}.listStyle(.insetGrouped)

iPhone simulator showing SwiftUI List with InsetGroupedListStyle applied, displaying rounded inset sections

And here’s .grouped:

List {
		//...
}.listStyle(.grouped)

iPhone simulator showing SwiftUI List with GroupedListStyle applied, displaying grouped sections

Here’s .sidebar:

iPhone simulator showing SwiftUI List with SidebarListStyle applied, displaying collapsible sections with dropdown arrows

Tagged: Swift · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about swift: