This overview introduces you to the core features of the Navigation framework and guides you through basic setup and implementation.
In your SwiftUI files, import Navigation:
import SwiftUI
import Navigation
Replace your existing NavigationStack
with the Navigation
view provided by the framework:
struct ContentView: View {
var body: some View {
Navigation {
// Your root view content
HomeView()
}
}
}
This automatically creates and injects a Navigator
instance into the environment.
Since the Navigator
is already injected into the environment by the Navigation
view, you can access it in your child views using the @EnvironmentObject
property wrapper:
struct SomeView: View {
@EnvironmentObject var navigator: Navigator
var body: some View {
// Your view content
}
}
Leverage SwiftUI's NavigationLink
for standard navigation:
NavigationLink(value: YourDestinationType()) {
Text("Go to Detail View")
}
.navigationDestination(
for: YourDestinationType.self,
destination: { destination in
// Destination view
DetailView(data: destination)
}
)
Programmatically navigate by modifying the navigation path:
navigator.append(
YourDestinationType()
)
Simplify navigation with NavigatorButton
:
NavigatorButton(
action: { navigator in
navigator.append(YourDestination())
},
label: {
Text("Navigate")
}
)
navigator.sheet(
content: {
// Sheet content
SheetView()
},
onDismiss: {
// Optional dismissal action
}
)
navigator.alert(
title: "Alert Title",
message: {
Text("This is an alert message.")
},
actions: {
NavigatorButton("OK") { $0.dismiss() }
}
)
navigator.confirmDialog(
title: "Confirm Action",
message: {
Text("Are you sure you want to proceed?")
},
actions: {
NavigatorButton("Yes") { $0.dismiss() }
NavigatorButton("No") { $0.dismiss() }
}
)
Use the dismiss()
method to close the current modal or navigate back:
navigator.dismiss()
Explore how to manage modals, alerts, and confirmation dialogs using the Navigation framework.