Add a NavigationStack in SwiftUI
Written by Team Kodeco
When building an app with multiple views, it is important to have a way to navigate between them. In SwiftUI, the NavigationStack provides a simple and intuitive way to navigate between views.
To add a NavigationStack to your SwiftUI app, wrap your top-level view in a NavigationStack. Within the NavigationStack, you can add multiple views as navigation items. Each navigation item is represented as a button on the navigation bar, which the user can tap to navigate to that view.
Here’s an example of how to add a NavigationStack to your SwiftUI app:
struct ContentView: View {
var body: some View {
NavigationStack {
Text("Welcome to my app!")
.navigationTitle("Home")
.navigationBarTitleDisplayMode(.large)
}
}
}
In this example, a Text view is encapsulated within a NavigationStack. The navigationTitle modifier is used to establish the text that appears on the navigation bar. The navigationBarTitleDisplayMode modifier sets the display mode of the navigation bar title, which, in this case, is set to .large.
To add another view as a navigation item, the .toolbar modifier can be used as follows:
struct ContentView: View {
var body: some View {
NavigationStack {
VStack {
Text("Welcome to my app!")
NavigationLink(destination: DetailView()) {
Text("Go to Detail View")
}
}
.navigationTitle("Home")
.navigationBarTitleDisplayMode(.large)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
print("Settings tapped")
}) {
Text("Settings")
}
}
}
}
}
}
struct DetailView: View {
var body: some View {
Text("This is the detail view!")
.navigationTitle("Detail")
.navigationBarTitleDisplayMode(.large)
}
}
You should see the following in the preview:
In this example, we’ve incorporated a VStack with a Text view and a NavigationLink within our NavigationStack. The NavigationLink allows the user to navigate to the DetailView upon being tapped. We’ve also added a Settings button to the navigation bar using the .toolbar modifier and the ToolbarItem view.
For more details, consult the “Lists & Navigation in SwiftUI” section of this cookbook.