In this tutorial we are going to look at how to use NavigationStack in SwiftUI. In many apps you will have experienced a navigation interface. This type of UI typically consists of a navigation bar and a list of data, allowing users to navigate to a detailed view when they tap on the content.
In UIKit, we implement this type of interface using UINavigationController. In SwiftUI, we used the NavigationView component which is now called NavigationStack since iOS 16.
Implementing a Navigation Stack
To embed a list view in a NavigationStack, you simply needed to wrap the list with a NavigationStack like this:
NavigationStack{
List {
ForEach(restaurants) { restaurant in
BasicImageRow(restaurant: restaurant)
}
}
.listStyle(.plain)
}
Once you’ve done this you’ll see an empty navigation bar. To assign a title to the bar, insert the navigationBarTitle modifier as shown below:
NavigationStack{
List {
ForEach(restaurants) { restaurant in
BasicImageRow(restaurant: restaurant)
}
}
.listStyle(.plain)
.navigationTitle("Restaurants")
}
The result in XCode is as follows:
Customizing the Navigation Bar
By default, the navigation bar is set to appear as a long title. However, if you want to keep the navigation bar compact and disable the use of a long title you can do so with the navigationBarTitleDisplayMode modifier.
The parameter specifies the appearance of the navigation bar, determining whether it should appear as a long title or a compact title.
By default it is set to .automatic, meaning that the long title is used. In the following code, we set it to .inline, indicating to use a compact title.
.navigationBarTitleDisplayMode(.automatic)