SwiftUI Navigation navigationDestination

SwiftUI Navigation: navigationDestination

Define typed destinations for values pushed onto a NavigationStack path using .navigationDestination(for:).


Typed destinations

Typed destinations allow you to define destinations for values pushed onto a NavigationStack path using .navigationDestination(for:).

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

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

struct DestinationTypedDemo: View {
  @State private var intPath: [Int] = []
  @State private var stringPath: [String] = []
  var body: some View {
NavigationStack(path: $intPath) {
  VStack(spacing: 12) {
    Button("Push Int 7") { intPath.append(7) }
    NavigationLink("Push Text 'Hi'", value: "Hi")
  }
  .navigationDestination(for: Int.self) { n in NumberDetail(n: n) }
  .navigationDestination(for: String.self) { s in TextDetail(s: s) }
  .navigationTitle("Typed Destinations")
}
} }

In the example above, the NumberDetail and TextDetail views are used as destinations for values pushed onto a NavigationStack path using .navigationDestination(for:).



Enum-based routing

Enum-based routing allows you to define destinations for values pushed onto a NavigationStack path using .navigationDestination(for:).

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

enum Route: Hashable { case number(Int), text(String) }

struct DestinationMultiDemo: View {
  @State private var path: [Route] = []
  var body: some View {
NavigationStack(path: $path) {
  VStack(spacing: 12) {
    Button("Go to number 5") { path.append(.number(5)) }
    Button("Go to text 'Hello'") { path.append(.text("Hello")) }
  }
  .navigationDestination(for: Route.self) { r in
    switch r {
    case .number(let n): Text("Number: \(n)")
    case .text(let s): Text("Text: \(s)")
    }
  }
  .navigationTitle("Enum Destinations")
}
} }

Comments

Leave a Reply

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