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
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")
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View { NavLinkBasicDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}
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
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")
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View { NavLinkValueDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene { WindowGroup { ContentView() } }
}
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.