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

心不动则不痛 提交于 2021-02-10 15:44:09

问题


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")
        }
    }
}

回答1:


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)
            }
        )
    }
}


来源:https://stackoverflow.com/questions/63358275/how-can-i-pop-a-navigation-view-and-return-to-the-previous-view-rather-than-the

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!