Home > front end >  How to dismiss a SwiftUI NavigationView from a parent view
How to dismiss a SwiftUI NavigationView from a parent view

Time:07-28

Usually, to implement a "custom dismiss button" within a SwiftUI NavigationView, I would use @Environment(\.dismiss) private var dismiss, and then call dismiss() to dismiss the view.

However, suppose I want to dismiss a NavigationLink from a parent of the NavigationView?

struct SwiftUIView: View {
    var body: some View {
        HStack {
            Button(action: {
                // dismiss view
            }) {
                Text("Dismiss View")
            } // assume this button is always visible
            NavigationView {
                Text("This is the NavigationView")
                NavigationLink {
                    Text("This is the view I want to exit")
                } label: {
                    Text("Go to view I want to exit")
                }
            }
        }
    }
}

How would I go about dismissing the view displaying This is the view I want to exit, by clicking the Dismiss View button in the parent view?

CodePudding user response:

Here is the solution:

struct SwiftUIView: View {
    @State var isPresent = true
    @State var isDismissed: Bool = false
    
    var body: some View {
        HStack {
            Button(action: {
                isDismissed = true
            }) {
                Text("Dismiss View")
            } // assume this button is always visible
            
            NavigationView {
                VStack {
                    Text("This is the NavigationView")
                    NavigationLink {
                        ViewToDismiss(dismissView: $isDismissed)
                    } label: {
                        Text("Go to view I want to exit")
                    }
                }
            }
            
        }
    }
}

struct ViewToDismiss: View {
    @Environment(\.dismiss) private var dismiss
    @Binding var dismissView: Bool
    var body: some View {
        Text("This is the view I want to exit")
            .onChange(of: dismissView,
                      perform:
                        ( { newValue in
                dismiss()
            }))
    }
}
  • Related