gpt4 book ai didi

SwiftUI 侧边栏不记得状态

转载 作者:行者123 更新时间:2023-12-04 11:11:52 24 4
gpt4 key购买 nike

我有这个应用程序使用新的 侧边栏 在 iOS14 for iPad os 中引入,但我不明白为什么它不记得隐藏时的状态

这是侧边栏结构

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 ...
}
这是我在内容 View 中放置侧边栏的地方,你可以看到设备是否是 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")
}
}
}
}

最佳答案

List(selection: $selection)选择绑定(bind)仅适用于 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))
有关更多信息,请参阅此 answer .

关于SwiftUI 侧边栏不记得状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62760985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com