Revealed on: Could 22, 2024
One of many key options that was lacking from SwiftUI when it first shipped was a great way to do programmatic navigation. There have been some methods to deal with this earlier than iOS 16 launched NavigationPath nevertheless it wasn’t very satisfying to make use of these APIs and so they might be somewhat unreliable at instances. To see an instance, check out this submit I wrote about dealing with deeplinks on iOS 14.
On this submit, I’d wish to revisit programmatic navigation by way of iOS 16’s NavigationPath API which is a big leap ahead by way of developer expertise and reliability on the similar time.
On this submit we’ll have a look at:
- Understanding iOS 16’s navigation API
- Navigating by way of a NavigationPath
Understanding iOS 16’s navigation API
On iOS 16, Apple launched the NavigationStack view. It is a view that’s just about analogous to UIKit’s UINavigationController and it permits builders to implement stack-based navigation. That is the form of navigation that you simply’ll truly discover in most apps that permit you to navigate into gadgets which can be proven in an inventory for instance.
A navigation view in iOS has a stack of views that it holds on to as a hierarchy of how the consumer bought to the place they at the moment are. For instance, the basis view is likely to be an inventory, the subsequent view is likely to be a film view and the subsequent one is likely to be a view the place customers can view the forged of a film. Every view would exist on the stack and a consumer can navigate again one degree by swiping from the sting of their display screen.
I’m positive you’re aware of the UX of this.
The stack of views that represents the navigation hierarchy wasn’t out there to make use of till iOS 16. The primary distinction between UIKit’s UINavigationController and the way NavigationStack manages its navigation is that in SwiftUI we are able to truly navigate based mostly on fashions.
Because of this we are able to map cases of, for instance, a Film mannequin to a MovieView that may current a film to the consumer.
Basically because of this we are able to mannequin a navigation hierarchy utilizing mannequin knowledge somewhat than views.
Let’s check out an instance of how we are able to arrange a NavigationStack together with a element web page for a given mannequin kind. We gained’t introduce a NavigationPath simply but. Behind the scenes our NavigationStack will handle its personal path if we don’t present one so we’ll simply depend on that for now.
The code beneath defines a easy listing view with NavigationLink views to allow navigation. Discover that the NavigationLink receives a worth as an alternative of a vacation spot. Additionally, discover how we’re making use of a navigationDestination view modifier to specify a vacation spot view for our mannequin.
struct ContentView: View {
@State non-public var workouts: [Exercise] = Train.pattern
var physique: some View {
NavigationStack {
ExercisesList(workouts: workouts)
.navigationDestination(for: Train.self, vacation spot: { train in
ExerciseDetail(train: train)
})
}
}
}
struct ExercisesList: View {
let workouts: [Exercise]
var physique: some View {
Checklist(workouts) { train in
NavigationLink(worth: train, label: {
ExerciseListItem(train: train)
})
}
.navigationTitle("My workouts")
}
}
What’s particularly attention-grabbing right here is the place we apply the navigationDestination view modifier.
I selected so as to add it to my listing. Because of this any NavigationLink within my listing with an occasion of Train as its worth will use the vacation spot view that I offered as its view. Because of this I can outline my vacation spot views multi function place which implies that I can shortly motive about which view will likely be proven for a mannequin.
If I have been to outline a second navigationDestination for a similar mannequin kind on my Checklist, that second vacation spot would overwrite my first. This permits me to override the vacation spot if wanted so that every view can nonetheless explicitly outline its personal “exit views” nevertheless it’s not required. That is actually highly effective and permits for very versatile navigation setups.
At this level, we’re capable of push new fashions onto our navigation stack’s navigation path utilizing our navigation hyperlink and we’ve configured a vacation spot view utilizing the navigationDestination view modifier.
Now let’s arrange a navigation path so we are able to begin performing some programmatic navigation, lets?
Navigating with a NavigationPath
A NavigationStack may be arrange with a NavigationPath object which can permit you to achieve management over the stack’s navigation hierarchy.
The only method to arrange a NavigationPath is as follows:
struct ContentView: View {
@State non-public var workouts: [Exercise] = Train.pattern
@State non-public var path = NavigationPath()
var physique: some View {
NavigationStack(path: $path) {
ExercisesList(workouts: workouts)
.navigationDestination(for: Train.self, vacation spot: { train in
ExerciseDetail(train: train)
})
}
}
}
With this code, we’re not but doing something to achieve management of our navigation path. We’re simply making an occasion of NavigationPath and we go a binding to NavigationStack. Any further, every time we navigate to a brand new view, the mannequin that’s used as a price will likely be added to the trail we created.
Basically, when a consumer faucets on a NavigationLink, we take the mannequin occasion that was handed as a worth and it’s added to the navigation path routinely.
We will go any Hashable mannequin as the worth for a navigation vacation spot and we are able to additionally combine fashions. So we may go cases of Train, Int, String, and extra to the identical navigation path.
In reality, you usually don’t fear about which mannequin varieties you go. You simply go the mannequin that you want to draw your vacation spot view and also you let the system deal with every part else.
Let’s check out how we are able to substitute our NavigationLink with a Button so we are able to manually append our mannequin to the NavigationPath that we’ve created earlier than.
We will create a binding to the NavigationPath and we go it to the ExercisesList, permitting it to append new gadgets to the trail which can enable the NavigationStack to navigate to the vacation spot for our mannequin:
struct ContentView: View {
@State non-public var workouts: [Exercise] = Train.pattern
@State non-public var path = NavigationPath()
var physique: some View {
NavigationStack(path: $path) {
// 1
ExercisesList(workouts: workouts, path: $path)
.navigationDestination(for: Train.self, vacation spot: { train in
ExerciseDetail(train: train)
})
}
}
}
struct ExercisesList: View {
let workouts: [Exercise]
// 2
@Binding var path: NavigationPath
var physique: some View {
Checklist(workouts) { train in
Button(motion: {
// 3
path.append(train)
}, label: {
ExerciseListItem(train: train)
})
}
.navigationTitle("My workouts")
}
}
Earlier than I clarify the code, let me say that I don’t assume this can be a good thought. The code was higher with NavigationLink. That mentioned, the purpose of this instance is to demo placing gadgets in a NavigationPath programmatically which we are able to do from a button handler.
First, we go a binding to our navigation path to the listing view. Because of this now our NavigationStack and ExercisesList each have entry to the very same NavigationPath occasion.
The ExercisesList was up to date to take a binding to a NavigationPath, and we’ve swapped the NavigationLink out in favor of a Button. Within the button handler, I name append with the Train mannequin for the button on path. This can add the mannequin to the trail which can trigger SwiftUI to navigate to the vacation spot view for that mannequin.
That is actually cool!
Along with appending parts to the trail, we are able to truly take away gadgets from the trail too by calling take away on it.
We will even get the variety of gadgets on the trail to implement a “pop to root” fashion perform:
func popToRoot() {
path.removeLast(path.rely)
}
This perform will take away all parts from the navigation stack’s path, solely leaving its root to be displayed.
The API for NavigationPath is actually versatile. You may even add a number of views in a single go, ensuing within the final added view changing into the highest every one others being a part of the stack so the consumer sees them after they navigate again.
In Abstract
With NavigationPath we’ve gained a great deal of energy by way of with the ability to navigate programmatically. By leveraging model-based navigation we are able to signify a navigation stack’s hierarchy as knowledge somewhat than views, and we’re capable of go our NavigationPath round by way of bindings as a way to enable views to append new fashions to the trail.
Dealing with deeplinks and restoring navigation stacks with NavigationPath is hundreds higher than it was pre iOS 16 and I’m positive that Apple will maintain bettering NavigationPath over time to make managing navigation by way of code higher and higher.

