iOS SwiftUI: pop or dismiss view programmatically iOS SwiftUI: pop or dismiss view programmatically ios ios

iOS SwiftUI: pop or dismiss view programmatically


This example uses the new environment var documented in the Beta 5 Release Notes, which was using a value property. It was changed in a later beta to use a wrappedValue property. This example is now current for the GM version. This exact same concept works to dismiss Modal views presented with the .sheet modifier.

import SwiftUIstruct DetailView: View {    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>    var body: some View {        Button(            "Here is Detail View. Tap to go back.",            action: { self.presentationMode.wrappedValue.dismiss() }        )    }}struct RootView: View {    var body: some View {        VStack {            NavigationLink(destination: DetailView())            { Text("I am Root. Tap for Detail View.") }        }    }}struct ContentView: View {    var body: some View {        NavigationView {            RootView()        }    }}


SwiftUI Xcode Beta 5

First, declare the @Environment which has a dismiss method which you can use anywhere to dismiss the view.

import SwiftUIstruct GameView: View {        @Environment(\.presentationMode) var presentation        var body: some View {        Button("Done") {            self.presentation.wrappedValue.dismiss()        }    }}


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.

import SwiftUIstruct ContentView: View {    var body: some View {        NavigationView {            MasterView()        }    }}struct MasterView: View {    @State private 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 DEBUGstruct ContentView_Previews: PreviewProvider {    static var previews: some View {        ContentView()    }}#endif