How to Use NavigationStack in SwiftUI for Navigation
Use
NavigationStack in SwiftUI to manage navigation by wrapping your views and pushing new views onto the stack with NavigationLink. It replaces NavigationView for a more flexible and modern navigation experience.Syntax
NavigationStack wraps your content and manages the navigation path. Use NavigationLink inside it to navigate to new views.
NavigationStack { ... }: The container for navigation.NavigationLink(destination: View) { Label }: Creates a tappable link to push a new view.- Optionally, use a
pathbinding to control navigation programmatically.
swift
NavigationStack {
List(items, id: \.self) { item in
NavigationLink(destination: DetailView(item: item)) {
Text(item)
}
}
}Output
A list of items where tapping one pushes DetailView onto the navigation stack.
Example
This example shows a simple list of fruits. Tapping a fruit navigates to a detail screen showing the fruit name.
swift
import SwiftUI struct ContentView: View { let fruits = ["Apple", "Banana", "Cherry"] var body: some View { NavigationStack { List(fruits, id: \.self) { fruit in NavigationLink(destination: Text("You selected: \(fruit)")) { Text(fruit) } } .navigationTitle("Fruits") } } }
Output
Shows a list titled 'Fruits'. Tapping a fruit shows a new screen with text 'You selected: [Fruit]'.
Common Pitfalls
- Not wrapping your views inside
NavigationStackcausesNavigationLinkto not work. - Using
NavigationViewinstead ofNavigationStackin new projects misses out on modern features. - For programmatic navigation, forgetting to bind the
pathstate can cause navigation not to update.
swift
/* Wrong: NavigationLink outside NavigationStack */ var body: some View { NavigationLink(destination: Text("Detail")) { Text("Go") } } /* Right: Wrap in NavigationStack */ var body: some View { NavigationStack { NavigationLink(destination: Text("Detail")) { Text("Go") } } }
Output
Wrong: Link does nothing. Right: Tapping 'Go' navigates to 'Detail' screen.
Quick Reference
- NavigationStack: Container for navigation.
- NavigationLink: Pushes new views.
- path: Optional binding to control navigation programmatically.
- .navigationTitle(): Sets the title of the navigation bar.
Key Takeaways
Wrap your views inside NavigationStack to enable navigation.
Use NavigationLink to push new views onto the navigation stack.
NavigationStack replaces NavigationView for modern SwiftUI navigation.
Use a path binding for programmatic navigation control.
Always set navigation titles for better user experience.