Home > front end >  Dismiss navigation View in SwiftUI
Dismiss navigation View in SwiftUI

Time:11-10

I have 3 Views, let say view1, view2 and view3.

view1 is home screen.

Now, I am presenting view2 with naviagationView.

Now, on some event, I have pushed view 3 from view2.

So in short, scene is view1(home) -> presented NavigationView(view2) -> pushed view3

Now, from view3, I want to dismiss navigation view and wanted to come back to view1(home).

If I am taking presentationMode environment variable and make call as presentationMode.wrappedValue.dismiss, then it is popping up to view2, but I wanted to dismiss the whole navigationview.

Here, I have just pushed one view. But there are chances that I might have pushed 7-8 views and wanted to dismiss the full navigation view from there.

Is there any way to do this in swiftUI?

CodePudding user response:

The other day I realised that when you use a NavigationStack or a NavigationView, and you start presenting views using NavigationLink, if you long press the back button, it displays a menu with the names of all the previous views so you can choose where to go back. So if you have something like this with four levels:

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink("Go to second view") {
                NavigationLink("Go to third view") {
                    NavigationLink("Go to forth view"){
                        Text("The end")
                    }.navigationTitle("Third View").navigationBarTitleDisplayMode(.inline)
                }.navigationTitle("Second View").navigationBarTitleDisplayMode(.inline)
            }.navigationTitle("Home View").navigationBarTitleDisplayMode(.inline)
        }
    }
}

You will see this small menu

I also found this article https://www.macrumors.com/guide/ios-14-hidden-features/ and it seems to be a iOS 14 feature. The problem is that if your app is set to work with previous version of iOS, you will have to find another way to do it.

CodePudding user response:

Try this approach

struct ContentView: View {
    @State var id = UUID()
    
    var body: some View {
        NavigationView {
            NavigationLink {
                NavigationLink  {
                    VStack {
                        Text("Third")
                        Button {
                            id = UUID()
                        } label: {
                            Text("Clear Stack")
                        }
                    }.navigationTitle("Third")
                } label: {
                    Text("Go Third")
                }.navigationTitle("Second")
            } label: {
                Text("Go Second")
            }.navigationTitle("First")
        }.id(id)
    }
}
  • Related