SwiftUI Navigation Programmatic Navigation

SwiftUI Navigation: Programmatic Navigation

Control navigation in code using NavigationPath and typed destinations.


Path controls

NavigationPath controls the navigation path.

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

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

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

In the example above, the NavigationPath is used to control the navigation path.



Reset & multi-push

Reset the path and push multiple destinations.

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct ResetMultiPushDemo: View {
  @State private var path: [Int] = []
  var body: some View {
NavigationStack(path: $path) {
  VStack(spacing: 12) {
    Button("Reset to root") { path.removeAll() }
    Button("Go to 1 → 2 → 3") { path.append(contentsOf: [1,2,3]) }
  }
  .navigationDestination(for: Int.self) { n in Text("Screen #\(n)") }
  .navigationTitle("Reset & Multi-Push")
}
} }

Comments

Leave a Reply

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