I'm trying to do a simple SwiftUI navigation from one view to another and back using a bar button item. I have tried three different approaches to calling a new view. Using a Button in the body view works, but using NavigationBarItems in the navigation bar fails in two different ways.
Here's the start view:
struct ContentView: View {
@State private var showSecondView = false
var body: some View {
NavigationView {
VStack {
Text("This is the content view")
.navigationBarTitle("Nav Title")
//this works ONCE only:
.navigationBarItems(trailing: Button(action: {self.showSecondView.toggle()}) {
Text("SecondView")
})
//this always fails on return to contentview with error:
//Tried to pop to a view controller that doesn't exist
// .navigationBarItems(trailing:
// NavigationLink(destination: SecondView()) {
// Text("SecondNav")
// }
// )
//This always works:
Button(action: {self.showSecondView.toggle()} ) {
Text("Call Modal Second View")
}.padding()
Text(self.showSecondView ? "true" : "false")
}.sheet(isPresented: $showSecondView) {
SecondView()
}
}
}
}
If I use a NavigationLink in the NavigationBarItems, the SecondView is displayed, but on return to the ContentView, it crashes with the error: "Tried to pop to a view controller that doesn't exist"
If I use a Button in the NavigationBarItems, the transition to the SecondView works once and only once. The return to ContentView works but the button no longer functions. Interestingly, If the first action taken is with the Button in the Body, the NavigationBarItem does not work even once.
And the simple SecondView:
struct SecondView: View {
@Environment(\.presentationMode) var presentation
var body: some View {
NavigationView {
VStack{
Text("This is the second view")
Button(action: { self.presentation.wrappedValue.dismiss()}) {
Text("Dismiss Modal")
}.padding()
}
}
}
}
I'm confused. Any guidance would be appreciated. Xcode 11.2 (11B44), Catalina 10.15
Call Modal Second View
button or the top-rightSecondView
button without any issues. Also uncommenting the code and using the trailingNavigationLink(..)
works fine as well. – fulvio