我有这个应用程序使用 iOS14 中为 iPad 操作系统引入的新侧边栏,但我不明白为什么它不记得隐藏时的状态
这是侧边栏结构
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())
}
}
为了标记元素,我使用了一个名为 NavigationItem 的自定义结构
enum NavigationItem {
case agenda
case calendar
case ...
}
这里是我在内容视图中放置侧边栏的地方,你可以看到设备是否是 iPad(使用 sizeClasses 检测)我使用侧边栏,否则如果它是 iPhone,我使用 TabBar
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")
}
}
}
}