Reading time: 1 min

This recipe shows how to display a grouped list in SwiftUI. A grouped list contains sections, comprised of zero or more rows, plus an optional header and footer.

The end result will look like this:

grouped-insets

OK, so the formula is quite simple:

  1. Pass Sections as your List's items.
  2. Specify the appearance using listStyle modifier in your list's superview.

First, define a simple struct to model your sections:

struct Item: Hashable {
  let header: String
  let footer: String
  let rows: [String]
}

// ... and some sample data

let items = [
    Item(header: "Header 1", footer: "Footer 1", rows: ["A", "B", "C"]),
    Item(header: "Header 2", footer: "Footer 2", rows: ["C", "D"]),
    Item(header: "Header 3", footer: "Footer 3", rows: ["E"])
]

Then, implement the above formula in your view as following:

var body: some View {
  NavigationView {
    List {
      ForEach(items, id: \.self) { item in
        Section(header: Text(item.header), footer: Text(item.footer)) {
          ForEach(item.rows, id: \.self) { row in
            Text(row)
          }
        }
      }
    }
  }.listStyle(GroupedListStyle())
}

There are several ListStyles you can choose from starting from iOS 13:

  • If you omit the listStyle modifier, or pass DefaultListStyle or PlainListStyle, you get the following:

plain

  • GroupedListStyle makes this look like your regular UITableView.Style.grouped:

grouped

iOS 14 added two more options for grouped lists:

  • GroupedInsetsListStyle adds padding and round borders to the section's items:

grouped-insets

  • SidebarListStyle allows the user to collapse/expand sections:

ezgif-1-732837f534ae

Next Post Previous Post