I'm having a nested NavigationView Navigationflow. On lets say the second or third page I want to go back to the root view if a button gets pressed. I stumbled accross the code from here (SwiftUI - Is there a popViewController equivalent in SwiftUI?):
struct ContentViewRoot: View {
@State var pushed: Bool = false
var body: some View {
NavigationView{
VStack{
NavigationLink(destination:ContentViewFirst(pushed: self.$pushed), isActive: self.$pushed) { EmptyView() }
.navigationBarTitle("Root")
Button("push"){
self.pushed = true
}
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct ContentViewFirst: View {
@Binding var pushed: Bool
@State var secondPushed: Bool = false
var body: some View {
VStack{
NavigationLink(destination: ContentViewSecond(pushed: self.$pushed, secondPushed: self.$secondPushed), isActive: self.$secondPushed) { EmptyView() }
.navigationBarTitle("1st")
Button("push"){
self.secondPushed = true;
}
}
}
}
struct ContentViewSecond: View {
@Binding var pushed: Bool
@Binding var secondPushed: Bool
var body: some View {
VStack{
Spacer()
Button("PopToRoot"){
self.pushed = false
} .navigationBarTitle("2st")
Spacer()
Button("Pop"){
self.secondPushed = false
} .navigationBarTitle("1st")
Spacer()
}
}
}
It works for me with Bindings but I'm not sure if this is the best way to do it since it's really painfull to inject all the bindings in the different views. Is there any other way to achieve it?
That's the flow I'm trying to achieve: https://i.stack.imgur.com/QhdjL.gif
Thanks!