SwiftUI Navigation NavigationStack

SwiftUI Navigation: NavigationStack

Use NavigationStack as the container for pushing and popping views.

Use NavigationLink to create links that push views onto the stack.

Use .navigationDestination to specify the view to display when a link is selected.


NavigationStack Example

Push and pop views using NavigationLink and .navigationDestination.

Basic Stack Push

Basic Stack Push is when you push a view onto the stack and pop it when you tap a button.

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct Detail: View { let value: Int; var body: some View { Text("Detail: \(value)") } }

struct NavStackBasicDemo: View {
  var body: some View {
NavigationStack {
  List(1...5, id: \.self) { n in
    NavigationLink("Item \(n)", value: n)
  }
  .navigationDestination(for: Int.self) { n in Detail(value: n) }
  .navigationTitle("Items")
}
} }

In the example above, the NavigationLink is used to push a view onto the stack and the .navigationDestination is used to specify the view to display when a link is selected.



Programmatic Path

Programmatic Path is when you push a view onto the stack and pop it when you tap a button.

The difference between Basic Stack Push and Programmatic Path is that Programmatic Path uses a NavigationPath to manage the navigation state.

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct NumberDetail: View { let n: Int; var body: some View { Text("Number: \(n)") } }

struct NavStackPathDemo: View {
  @State private var path: [Int] = []
  var body: some View {
NavigationStack(path: $path) {
  VStack(spacing: 12) {
    Button("Go to 7") { path.append(7) }
    Button("Back") { if !path.isEmpty { _ = path.removeLast() } }
  }
  .navigationDestination(for: Int.self) { n in NumberDetail(n: n) }
  .navigationTitle("Path Demo")
}
} }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *