17

我有这个应用程序使用 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")
            }
        }
    }
}
4

2 回答 2

1

List(selection: $selection)选择绑定仅适用于 macOS。请参阅标题中的此评论:

/// On iOS and tvOS, you must explicitly put the list into edit mode for
/// the selection to apply.

作为一种解决方法,您可以使先前选择的行显示为粗体,例如

 NavigationLink(
        destination: HomeView(),
        tag: Screen.home,
        selection: $selection,
        label: {
            Label("Home", systemImage: "house" )
        })
        .font(Font.headline.weight(selection == Screen.home ? .bold : .regular))

有关更多信息,请参阅此答案

于 2020-10-26T19:09:43.627 回答
0

如果您不需要能够在侧边栏中选择多行,请将您的selection定义更改为:

@Binding var selection: NavigationItem?

警告:如果您有兴趣selection对 a 使用相同的变量TabView,那将不起作用。您需要定义另一个属性,因为NavigationItem不是可选的。

于 2021-05-25T23:01:23.403 回答