About NavigationLink Inside NavigationSplitView's Sidebar

Hello,

In the code below, I want to navigate back to the SecondView when pressing the back button in the ThirdView. However, it navigates to the FirstView instead. How can I make it navigate back to the SecondView without going to the FirstView?

struct FirstView: View {
    var body: some View {
        NavigationSplitView {
            Text("Here is the FirstView")
            NavigationLink("Go to SecondView") {
                SecondView()
            }
        } detail: {
            EmptyView()
        }
    }
}

struct SecondView: View {
    var body: some View {
        Text("Here is the SecondView")
        NavigationLink("Go to ThirdView") {
            Text("Here is the ThirdView")
        }
    }
}
Answered by Vision Pro Engineer in 792037022

Hi @kittens ,

You're seeing this behavior because the NavigationSplitView is collapsing down to a stack and showing content based on the content of the split view's columns. Here, it's showing the sidebar, and then navigating to the detail view, so the back button is taking you back to the sidebar no matter what.

To change this to the behavior you are looking for, you can put a NavigationStack in the detail view. For example:

 NavigationSplitView {
            Text("Here is the FirstView")
            NavigationLink("Go to SecondView") {
                SecondView()
            }
        } detail: {
            NavigationStack {
                Text("nothing selected yet")
            }
}

Hope this helps,

Sydney

Accepted Answer

Hi @kittens ,

You're seeing this behavior because the NavigationSplitView is collapsing down to a stack and showing content based on the content of the split view's columns. Here, it's showing the sidebar, and then navigating to the detail view, so the back button is taking you back to the sidebar no matter what.

To change this to the behavior you are looking for, you can put a NavigationStack in the detail view. For example:

 NavigationSplitView {
            Text("Here is the FirstView")
            NavigationLink("Go to SecondView") {
                SecondView()
            }
        } detail: {
            NavigationStack {
                Text("nothing selected yet")
            }
}

Hope this helps,

Sydney

About NavigationLink Inside NavigationSplitView's Sidebar
 
 
Q