Adding sections to a list
In this recipe, we will create an app that implements a static list with sections. The app will display a list of countries grouped by continent.
Getting ready
Let’s start by creating a new SwiftUI app in Xcode named ListWithSections
.
How to do it…
We will add a Section
view to our List
to separate groups of items by section titles. Proceed as follows:
- (Optional) Open the
ContentView.swift
file and replace thebody
content with aNavigationStack
. Wrapping theList
in aNavigationStack
allows us to add a title and navigation items to the view:NavigationStack { }
- Add a list and section to
NavigationStack
(or body view if you skipped the optional Step 1). Also, add alistStyle
andnavigationTitle
andnavigationBarTitleDisplayMode
modifiers:List { Section(header: Text("North America")){ Text("USA") Text("Canada") Text("Mexico...