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:
-
Item
is a struct that conforms to theIdentifiable
protocol. This protocol is used to uniquely identify elements. It’s particularly helpful inList
andForEach
where SwiftUI needs to identify views across state changes. TheItem
struct has anid
property that is automatically assigned a uniqueUUID
and aname
property. -
ContentView
is a SwiftUIView
that represents a view hierarchy. -
sectionsAndItems
is a dictionary where the keys are strings representing section titles and the values are arrays ofItem
objects that belong to that section. - The
body
property is a computed property that defines the view’s content. It uses aNavigationStack
to wrap the content, and aList
to display a list of items. - The
List
contains aForEach
loop that iterates over an array of section titles (the keys from thesectionsAndItems
dictionary). Each iteration creates aSection
view that represents a section in the list. TheSection
’s header is set to the section title. - Inside each
Section
view, there’s anotherForEach
loop that iterates over the items that belong to that section (retrieved from thesectionsAndItems
dictionary 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 aText
view displaying the item’s name. - 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!