If I’m using NavigationStack
and somewhere in the fourth or fifth view I need to rewind and send the user back three or four views, is there a way to do that programmatically?
I realize I can set an environment variable that on appear dismisses screens sending the user back a few views, but that sounds kludgy.
struct MainMenu: View {
var body: some View {
NavigationStack {
VStack{
List{
NavigationLink {
InvoiceMenu()
} label: {
MenuButton(choice: "invoice")
}
}
}
}
}
}
You do programatic navigation by using the navigation stack’s path
input, which is bound to an array. The array controls which items in the navigation stack are presented. E.g. if I had:
@State var array = [Int]()
NavigationStack(path: $array) { items }
You could append to the array to add an item on the navigation stack, and then call the .removeLast()
method on the array 4 times to go back 4 screens.
Paul explain these topics masterfully on YouTube:
- Handling navigation the smart way with navigationDestination()
- Programmatic navigation with NavigationStack