SwiftUI - Is there a popViewController equivalent in SwiftUI?

后端 未结 13 2122
说谎
说谎 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:10

    There is now a way to programmatically pop in a NavigationView, if you would like. This is in beta 5.

    Notice that you don't need the back button. You could programmatically trigger the showSelf property in the DetailView any way you like. And you don't have to display the "Push" text in the master. That could be an EmptyView(), thereby creating an invisible segue.

    (The new NavigationLink functionality takes over the deprecated NavigationDestinationLink)

    import SwiftUI
    
    struct ContentView: View {
        var body: some View {
            NavigationView {
                MasterView()
            }
        }
    }
    
    struct MasterView: View {
        @State var showDetail = false
    
        var body: some View {
            VStack {
                NavigationLink(destination: DetailView(showSelf: $showDetail), isActive: $showDetail) {
                    Text("Push")
                }
            }
        }
    }
    
    struct DetailView: View {
        @Binding var showSelf: Bool
    
        var body: some View {
            Button(action: {
                self.showSelf = false
            }) {
                Text("Pop")
            }
        }
    }
    
    #if DEBUG
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }
    #endif
    

提交回复
热议问题