< Programmatic navigation with NavigationStack | How to make a NavigationStack return to its root view programmatically > |
Navigating to different data types takes one of two forms. The simplest is when you're using navigationDestination()
with different data types but you aren't tracking the exact path that's being shown, because here things are straightforward: just add navigationDestination()
multiple times, once for each type of data you want.
For example, we could show five numbers and five strings and navigate to them differently:
NavigationStack {
List {
ForEach(0..<5) { i in
NavigationLink("Select Number: \(i)", value: i)
}
ForEach(0..<5) { i in
NavigationLink("Select String: \(i)", value: String(i))
}
}
.navigationDestination(for: Int.self) { selection in
Text("You selected the number \(selection)")
}
.navigationDestination(for: String.self) { selection in
Text("You selected the string \(selection)")
}
}
However, things are more complicated when you want to add in programmatic navigation, because you need to be able to bind some data to the navigation stack's path. Previously I showed you how to do this with an array of integers, but now we might have integers or strings so we can't use a simple array any more.
SwiftUI's solution is a special type called NavigationPath
, which is able to hold a variety of data types in a single path. In practice it works very similarly to an array – we can make a property using it, like this:
@State private var path = NavigationPath()
Bind that to a NavigationStack
:
NavigationStack(path: $path) {
Then push things to it programmatically, for example with toolbar buttons:
.toolbar {
Button("Push 556") {
path.append(556)
}
Button("Push Hello") {
path.append("Hello")
}
}
If you want to feel fancy, NavigationPath
is what we call a type-eraser – it stores any kind of Hashable
data without exposing exactly what type of data each item is.
TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.