Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Implement Section Headers in a List in SwiftUI
Written by Team Kodeco

Adding section headers in a SwiftUI list can help users navigate through the items by grouping them logically. This is particularly useful when dealing with larger lists.

In SwiftUI, section headers can be added to a list using the Section view. Each Section can contain a header and its own unique list of items.

Here’s an example of how to implement section headers in SwiftUI:

struct Item: Identifiable {
  let id = UUID()
  let name: String
}

struct ContentView: View {
  let sectionsAndItems: [String: [Item]] = [
    "Section 1": [
      Item(name: "Item 1"),
      Item(name: "Item 2")
    ],
    "Section 2": [
      Item(name: "Item 3"),
      Item(name: "Item 4")
    ]
  ]

  var body: some View {
    NavigationStack {
      List {
        ForEach(Array(sectionsAndItems.keys), id: \.self) { section in
          Section(header: Text(section)) {
            ForEach(sectionsAndItems[section] ?? []) { item in
              Text(item.name)
            }
          }
        }
      }
      .navigationTitle("My List")
    }
  }
}

Your preview should look like this:

A list with sections and section headers in SwiftUI.
A list with sections and section headers in SwiftUI.

In this example, we’ve used a dictionary to map each section to its corresponding items, making the structure of the data clearer and the code easier to read.

Here’s how this code works:

  1. Item is a struct that conforms to the Identifiable protocol. This protocol is used to uniquely identify elements. It’s particularly helpful in List and ForEach where SwiftUI needs to identify views across state changes. The Item struct has an id property that is automatically assigned a unique UUID and a name property.
  2. ContentView is a SwiftUI View that represents a view hierarchy.
  3. sectionsAndItems is a dictionary where the keys are strings representing section titles and the values are arrays of Item objects that belong to that section.
  4. The body property is a computed property that defines the view’s content. It uses a NavigationStack to wrap the content, and a List to display a list of items.
  5. The List contains a ForEach loop that iterates over an array of section titles (the keys from the sectionsAndItems dictionary). Each iteration creates a Section view that represents a section in the list. The Section’s header is set to the section title.
  6. Inside each Section view, there’s another ForEach loop that iterates over the items that belong to that section (retrieved from the sectionsAndItems dictionary using the section title as the key). If there are no items for the section (if sectionsAndItems[section] is nil), the ?? operator provides an empty array as a fallback. Each item in the section is represented by a Text view displaying the item’s name.
  7. The List has a navigation title set to “My List”.

By using the Section view in SwiftUI, adding section headers to your lists becomes a straightforward process. This provides an easy way to enhance the structure and usability of your list-based user interfaces. Happy coding!

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.