Luc*_*uca 15 sidebar swiftui ipados ios14 xcode12
我有这个应用程序使用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())
}
}
Run Code Online (Sandbox Code Playgroud)
为了标记元素,我使用了一个名为 NavigationItem 的自定义结构
enum NavigationItem {
case agenda
case calendar
case ...
}
Run Code Online (Sandbox Code Playgroud)
这是我在内容视图中放置侧边栏的地方,你可以看到设备是否是 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")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
List(selection: $selection)选择绑定仅适用于 macOS。请参阅标题中的此评论:
/// On iOS and tvOS, you must explicitly put the list into edit mode for
/// the selection to apply.
Run Code Online (Sandbox Code Playgroud)
作为解决方法,您可以使先前选择的行显示为粗体,例如
NavigationLink(
destination: HomeView(),
tag: Screen.home,
selection: $selection,
label: {
Label("Home", systemImage: "house" )
})
.font(Font.headline.weight(selection == Screen.home ? .bold : .regular))
Run Code Online (Sandbox Code Playgroud)
更多内容请参阅此答案。
| 归档时间: |
|
| 查看次数: |
1670 次 |
| 最近记录: |