jh95
jh95

Reputation: 399

How can I pop a navigation view and return to the previous view rather than the root view SwiftUI?

I have a ContentView that is the root view that navigates to a DetailView. The DetailView has a navbaritem that navigates to Help2 view. I want to click a button to dismiss the Help2 view and return to the DetailView (the view from which Help2 came from).

Currently, when I press a button on the Help2 view, it dismisses the view, but it returns me to the root ContentView rather than DetailView. If I navigate to the Help2 view then manually click the back button to navigate to DetailView, it will go to DetailView. Then, if I immediately click on the navbaritem to get back to the Help2 view, then click the button to dismiss the view, it will go to DetailView instead of ContentView as expected.

ContentView:

struct ContentView: View {
var body: some View {
    NavigationView {
        VStack {
            NavigationLink(destination: DetailView()) {
                Text("Show Detail View")
            }.navigationBarTitle("Navigation")
        }
    }
  }
}

DetailView:

struct DetailView: View {
@Environment(\.presentationMode) var presentationMode

var body: some View {
    VStack{
        Button(action: {
            self.presentationMode.wrappedValue.dismiss()
        })
        {
            Text("Root")
        }
    }
    .navigationBarTitle("DetailView", displayMode: .inline)
    .navigationBarItems(trailing:
        NavigationLink(destination: Help2()){
            Image(systemName: "plus").imageScale(.medium)
        }
    )
  }
}

Help2:

struct Help2: View {
@Environment(\.presentationMode) var presentationMode

var body: some View {
    Button(action: {
        self.presentationMode.wrappedValue.dismiss()
    })
        {
            Text("DetailView")
        }
    }
}

Upvotes: 1

Views: 3198

Answers (1)

pawello2222
pawello2222

Reputation: 54611

A possible solution may be to move NavigationLink outside the .navigationBarItems:

struct DetailView: View {
    @Environment(\.presentationMode) var presentationMode
    @State var isLinkActive = false

    var body: some View {
        VStack {
            Button(action: {
                self.presentationMode.wrappedValue.dismiss()
            })
            {
                Text("Root")
            }
        }
        .background(
            NavigationLink(destination: Help2(), isActive: $isLinkActive) {
                EmptyView()
            }
            .hidden()
        )
        .navigationBarTitle("DetailView", displayMode: .inline)
        .navigationBarItems(trailing:
            Button(action: {
                self.isLinkActive = true
            }) {
                Image(systemName: "plus").imageScale(.medium)
            }
        )
    }
}

Upvotes: 1

Related Questions