我有一个嵌套的 NavigationView 导航流。如果按下按钮,可以说第二页或第三页我想返回到根视图。我从这里 (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()
}
}
}
它适用于绑定,但我不确定这是否是最好的方法,因为在不同的视图中注入所有绑定真的很痛苦。还有其他方法可以实现吗?
这就是我想要实现的流程: https://i.stack.imgur.com/QhdjL.gif
谢谢!