Home > Software engineering >  How to dismiss multiple navgation view at once
How to dismiss multiple navgation view at once

Time:01-07

Here I have a view A, B, and C which have the following definitions and navigation flow. Here how can I go from view C to directly A by dismissing both B and C?

I am using this code to dismiss view C and B

@Environment(\.presentationMode) var presentationMode

presentationMode.wrapedValue.dismiss(

)

how can I dismiss at once? dismissing one by one makes the user experience quite disappointing ios : 13

struct A: View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: B()) {
                    Text("Go to B")
                }
            }
        }
    }
}

struct B: View {
    var body: some View {
        VStack {
            Text("This is view B")
            NavigationLink(destination: C()) {
                Text("Go to C")
            }
        }
    }
}

struct C: View {
    var body: some View {
        Text("This is view C")
    }
}

CodePudding user response:

You can use @Binding and change the value(isStartShow) in last structure to go to the start. But you can't use the standard button in navigation bar, you will need to make your own button as in the example

struct A: View {
    @State private var isAstive = false
    
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(isActive: $isAstive) {
                    B(isActive: $isAstive)
                } label: {
                    Text("Go to B")
                }
            }
        }
    }
}

struct B: View {
    @Binding var isActive: Bool
    
    var body: some View {
        VStack {
            Text("This is view B")
            
            NavigationLink(destination: C(isStartShow: $isActive)) {
                Text("Go to C")
            }
        }
    } 
}

struct C: View {
    @Binding var isStartShow: Bool
    
    var body: some View {
        Text("This is view C")
            // your custom button:
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button {
                        isStartShow.toggle()
                    } label: {
                        HStack {
                            Image(systemName: "chevron.backward")
                            Text("Back to main")
                                .foregroundColor(.blue)
                        }
                    }
                }
            }
            .navigationBarBackButtonHidden(true)
    }
}

video example

  • Related