I have an app using an NavigationSplitView with a list on the left and detail views on the right. When I select an item from the list on the left, the detail view on the should change and each detail view can push other views. I use a Navigation Stack in each root detail view. The NavigationStack does not seem to be working as expected.
I created a simple example app to show what I am seeing. In the app:
- Select Atlantic from the list on the left
- Tap on Atlantic View in the detail view to push to Atlantic Pushed View
- Select Pacific from the list on the left
The view on the right still shows Atlantic Pushed View when I would expect it to show Pacific View. If on the detail view I tap the back arrow, it goes from Atlantic Pushed View to Pacific View which is not right.
It seems like when I selected Pacific from the left, it replace the root Atlantic view with the root Pacific view in the NavigationStack which is not correct. It also seems like no matter what I try, there is only one NavigationStack path used throughout the app.
The behavior I want and would expect is:
- Select Atlantic from the list on the left
- Tap on Atlantic View in the detail view to push to Atlantic Pushed View
- Select Pacific from the list on the left, which which should show Pacific View
- Select Atlantic from the list on the left, which should go back to Pushed Atlantic View
I am considering filing a big report but I wanted to see if I am missing something or is this just not working. My sample code it below.
import SwiftUI
struct Ocean: Identifiable, Hashable {
let id: String
}
private var oceans = [
Ocean(id: "Atlantic"),
Ocean(id: "Pacific"),
]
struct ContentView: View {
@State var selection: Set<String> = [oceans[0].id]
var body: some View {
NavigationSplitView {
List(oceans, selection: $selection) { ocean in
Text("\(ocean.id) Ocean")
}
.navigationTitle("Oceans")
} detail: {
if selection.first == "Atlantic" {
AtlanticView(selection: selection)
}
else if selection.first == "Pacific" {
PacificView(selection: selection)
}
else {
Text("Unknown Ocean")
}
}
}
}
struct AtlanticView: View {
@State var selection: Set<String>
@State private var atlanticPath = NavigationPath()
var body: some View {
NavigationStack(path: $atlanticPath ) {
VStack {
NavigationLink {
AtlanticPushedView(selection: selection)
} label: {
Text("Atlantic View\n\(selection.first!) Ocean")
}
}
}
}
}
struct AtlanticPushedView: View {
var selection: Set<String>
var body: some View {
Text("Pushed View\n\(selection.first!) Ocean")
}
}
struct PacificView: View {
var selection: Set<String>
@State private var pacificPath = NavigationPath()
var body: some View {
NavigationStack(path: $pacificPath ) {
NavigationLink {
PacificPushedView(selection: selection)
} label: {
Text("Pacific View\n\(selection.first!) Ocean")
}
}
}
}
struct PacificPushedView: View {
var selection: Set<String>
var body: some View {
Text("Pacific Pushed View\n\(selection.first!) Ocean")
}
}