SwiftUI Sidebar doesn't remember state

I Have this app that uses the new sidebar introduced in iOS14 for iPad os but I can't figure out why it doesn't remember the state when its hidden

here is the stack overflow question where I've posted a gif of the problem

StackOverflow Question (w/ Video)

This is the sidebar struct

Code Block swift
import SwiftUI
struct Sidebar: View {
@Environment(\.managedObjectContext) var moc
@Binding var selection : Set<NavigationItem>
var body: some View {
List(selection: $selection) {
NavigationLink(destination: AgendaView().environment(\.managedObjectContext, moc).navigationTitle("Agenda"), label: {
Label("Agenda", systemImage: "book")
})
.tag(NavigationItem.agenda)
NavigationLink(destination: Text("Subjects"), label: {
Label("Materie", systemImage: "tray.full")
})
.tag(NavigationItem.subjects)
NavigationLink(destination: Text("Calendario"), label: {
Label("Calendario", systemImage: "calendar")
})
.tag(NavigationItem.calendar)
NavigationLink(destination: SettingsView().environment(\.managedObjectContext, moc).navigationTitle("Impostazioni"), label: {
Label("Impostazioni", systemImage: "gear")
})
.tag(NavigationItem.settings)
}
.listStyle(SidebarListStyle())
}
}


for tagging the elements I use a custom struct called NavigationItem

Code Block swift
enum NavigationItem {
case agenda
case calendar
case ...
}


and here is where I placed the Sidebar in the content view, as you can see if the device is an iPad (detected using sizeClasses) I use the sidebar, otherwise if its an iPhone I use the TabBar

Code Block swift
import SwiftUI
struct ContentView: View {
@Environment(\.horizontalSizeClass) var horizontalSizeClass
@Environment(\.managedObjectContext) var moc
@State private var selection : Set<NavigationItem> = [.agenda]
@ViewBuilder
var body: some View {
if horizontalSizeClass == .compact {
TabBar(selection: $selection)
.environment(\.managedObjectContext, moc)
} else {
NavigationView {
Sidebar(selection: $selection)
.environment(\.managedObjectContext, moc)
.navigationTitle("Menu")
}
}
}
}

I'm running into this same issue. I'm not sure how to resolve it or if it's just a bug. Apple's production iOS 14 apps that use sidebar navigation don't have this issue, but their Fruta sample app does. The same "forgetting" of selection state happens in portrait mode on iPad as well.
Same issue here in Xcode 12.2. Can't believe it hasn't been fixed yet.
I need a fix for this too, Sample project is Fruta with the Mac checkbox enabled. The sidebar item is not selected by default. Also when navigating through the selection parameter of NavigationLink will not visually select the item.

I used the same was as the Fruta app and with Xcode 13.2 and iPad Pro iOS 15.2 Simulator there is the behaviour as expected. I think Apple fixed it with Xcode 13. In my case it works pretty fine.

SwiftUI Sidebar doesn't remember state
 
 
Q