SwiftUI - 嵌套导航视图:回到根目录

时间:2020-12-20 10:20:15

标签: swiftui navigationview

我有一个嵌套的 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

谢谢!

0 个答案:

没有答案
相关问题