SwiftUI Navigation NavigationLink

SwiftUI Navigation: NavigationLink

Use NavigationLink to push a destination view when tapped.


Basic destination

The basic NavigationLink is used to push a destination view when tapped.

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct Detail: View { var body: some View { Text("Detail") } }

struct NavLinkBasicDemo: View {
  var body: some View {
NavigationStack {
  NavigationLink("Go to Detail", destination: Detail())
    .navigationTitle("Home")
}
} }

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.



Value-based link

The value-based NavigationLink is used to push a destination view when tapped.

Use NavigationLink(value:) with a typed 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 NavLinkValueDemo: View {
  var body: some View {
NavigationStack {
  VStack(spacing: 12) {
    NavigationLink("Go to 99", value: 99)
  }
  .navigationDestination(for: Int.self) { n in NumberDetail(n: n) }
  .navigationTitle("Value Links")
}
} }

Comments

Leave a Reply

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