< Handling navigation the smart way with navigationDestination() | Navigating to different data types using NavigationPath > |
Programmatic navigation allows us to move from one view to another just using code, rather than waiting for the user to take a specific action. For example, maybe your app is busy processing some user input and you want to navigate to a result screen when that work is finished – you want the navigation to happen automatically when you say so, rather than as a direct response to user input.
In SwiftUI this is done by binding the path of a NavigationStack
to an array of whatever data you're navigating with. So, we might start with this:
struct ContentView: View {
@State private var path = [Int]()
var body: some View {
NavigationStack(path: $path) {
VStack {
// more code to come
}
.navigationDestination(for: Int.self) { selection in
Text("You selected \(selection)")
}
}
}
}
That does two important things:
@State
property to store an array of integers.path
of our NavigationStack
, meaning that changing the array will automatically navigate to whatever is in the array, but also changes the array as the user presses Back in the navigation bar.So, we could replace the // more code to come
with buttons such as these:
Button("Show 32") {
path = [32]
}
Button("Show 64") {
path.append(64)
}
In the first button we're setting the whole array so that it just contains the number 32. If anything else happened to be in the array it will be removed, meaning that the NavigationStack
will return to its original state before navigating to the number 32.
In the second button we're appending 64, meaning that it will be added to whatever we were navigating to. So, if our array already contained 32, we'd now have three views in the stack: the original view (called the "root" view), then something to show the number 32, and finally something to show the number 64.
You can also push multiple values at the same time, like this:
Button("Show 32 then 64") {
path = [32, 64]
}
That will present a view for 32 then a view for 64, so the user needs to tap Back twice to get back to the root view.
You can mix user navigation and programmatic navigation as much as you want – SwiftUI will take care of making sure your path
array stays in sync with whatever data you show, regardless of how it's shown.
SPONSORED AppSweep by Guardsquare helps developers automate the mobile app security testing process with fast, free scans. By using AppSweep’s actionable recommendations, developers can improve the security posture of their apps in accordance with security standards like OWASP.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.