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:
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:
-
Itemis a struct that conforms to theIdentifiableprotocol. This protocol is used to uniquely identify elements. It’s particularly helpful inListandForEachwhere SwiftUI needs to identify views across state changes. TheItemstruct has anidproperty that is automatically assigned a uniqueUUIDand anameproperty. -
ContentViewis a SwiftUIViewthat represents a view hierarchy. -
sectionsAndItemsis a dictionary where the keys are strings representing section titles and the values are arrays ofItemobjects that belong to that section. - The
bodyproperty is a computed property that defines the view’s content. It uses aNavigationStackto wrap the content, and aListto display a list of items. - The
Listcontains aForEachloop that iterates over an array of section titles (the keys from thesectionsAndItemsdictionary). Each iteration creates aSectionview that represents a section in the list. TheSection’s header is set to the section title. - Inside each
Sectionview, there’s anotherForEachloop that iterates over the items that belong to that section (retrieved from thesectionsAndItemsdictionary using the section title as the key). If there are no items for the section (ifsectionsAndItems[section]isnil), the??operator provides an empty array as a fallback. Each item in the section is represented by aTextview displaying the item’s name. - The
Listhas 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!