SwiftUI - Is there a popViewController equivalent in SwiftUI?

后端 未结 13 2061
说谎
说谎 2020-12-12 20:18

I was playing around with SwiftUI and want to be able to come back to the previous view when tapping a button, the same we use popViewController inside a

13条回答
  •  有刺的猬
    2020-12-12 21:12

    With State Variables. Try that.

    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()
            }
        }
    }
    

提交回复
热议问题