Like many applications, mine involves navigation where the user starts a process on one screen and then progresses through several more steps to reach a conclusion. When he confirms that choice, I need to dismiss the entire stack. In my case, he's browsing contacts, selecting one, and then selecting a communication method from those offered by the contact.
This still appears to be a PITA in SwiftUI. NavigationPath is supposed to provide a way to programmatically control a stack of views. Well... I can't find a single example of how to use it for this, except with absurdly shallow (as in a single level) of child views that all take the same datatype.
Nowhere do I see how to use the path as users proceed through your view hierarchy with NavigationLinks. I have not seen any example of how elements get added to the path or how they are related to each added view. Nor can I find an example of popping views off the stack by removing related elements from the path.
I created a class that encloses a NavigationPath:
@Observable
class NavPathController
{
var path: NavigationPath
init()
{
path = NavigationPath()
}
func popOne()
{
path.removeLast()
}
func popAll()
{
path.removeLast(path.count)
}
}
In my root view, I pass a binding to this controller's NavigationPath when creating the NavigationStack:
@State private var viewStack = NavPathController()
var body: some View
{
NavigationStack(path: $viewStack.path)
{
VStack()
{
NavigationLink(destination: UserFindingView(viewPathController: viewStack), label: { Text("Pick a recipient") })
}
}
And likewise each view passes the same view-path controller object to each child view that's invoked with a NavigationLink (instead of using an environment variable, because I find those hokey). But in the end, the path is empty; not surprisingly, clearing it does not pop the views.
So how is one supposed to make this work?
Topic:
UI Frameworks
SubTopic:
SwiftUI