0
0
Ios-swiftHow-ToBeginner ยท 3 min read

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 path binding 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 NavigationStack causes NavigationLink to not work.
  • Using NavigationView instead of NavigationStack in new projects misses out on modern features.
  • For programmatic navigation, forgetting to bind the path state 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.