I have a NavigationSplitView with a Sidebar and Detail view. When selecting an item from the sidebar, the Detail view is updated to show what was selected. This all works fine so far on both an iPhone and an iPad.
However, on an iPhone, when returning back to the sidebar view to select something else, the previously selected item is being set to nil.
On an iPad it is not setting the previously selected item to nil, even if you hide and show the sidebar, it still remembers the previously selected entry.
I have tried with the iPhone simulator and on a physical device too.
To reproduce the issue, select an entry from the sidebar, the detail is shown/updated showing what was selected. Return back to the sidebar view and you can see for about half a second the previously selected item, then it gets set to nil.
Why is the selection being reset back to nil on the iPhone when returning back to the Sidebar view?
Please see very small complete code below:
import SwiftUI
struct ContentView: View {
@State private var selection: String?
var body: some View {
NavigationSplitView {
SidebarView(selection: $selection)
} detail: {
DetailView(selection: $selection)
}
}
}
struct SidebarView: View {
@Binding var selection: String?
let people = ["Finn", "Leia", "Luke", "Rey"]
var body: some View {
List(people, id: \.self, selection: $selection) { person in
Text(person)
}
Text("selection = \(String(describing: selection))")
}
}
struct DetailView: View {
@Binding var selection: String?
var body: some View {
Text("selectedItem = \(String(describing: selection))")
}
}
//------------------------
#Preview {
ContentView()
}