如何弹出导航视图并返回到上一个视图而不是根视图SwiftUI?

时间:2020-08-11 12:34:58

标签: ios swift swiftui

我有一个ContentView,它是导航到DetailView.的根视图。DetailView有一个navbaritem,可以导航到Help2视图。 我要单击一个按钮以关闭Help2视图并返回到DetailView Help2来自的视图)。

当前,当我按下Help2视图上的按钮时,它关闭了该视图,但是它将我返回到根ContentView而不是DetailView。如果我导航到Help2视图,然后手动单击后退按钮导航到DetailView,它将转到DetailView。然后,如果我立即单击navbaritem返回到Help2视图,然后单击该按钮以关闭该视图,它将转到DetailView而不是ContentView如预期的那样。

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

帮助2

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

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

1 个答案:

答案 0 :(得分:1)

可能的解决方案可能是将.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) } ) } } 之外:

excelFile = tempfile.gettempdir() + "\\" + "Employees.xlsx"
wkb.save(excelFile)
subprocess.Popen(excelFile, shell=True)