You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

macOS Ventura下如何选中NavigationView列表中的首个项?

解决macOS Ventura中NavigationView侧边栏首项无法选中的问题

在macOS Ventura及后续版本中,NavigationView的侧边栏选择逻辑发生了变化,原来基于多选集合Set<Int>的绑定方式不再能自动触发NavigationLink的选中状态和对应视图加载。针对你的场景,改用单选绑定类型就能解决问题,具体调整如下:

核心改动点

  • 将多选的Set<Int>类型的selection改为单选的Int?(可选整数),更匹配侧边栏单选的使用场景
  • 为所有需要参与选择的NavigationLink添加对应tag(你之前仅给第一个项加了tag,其他项也需要补全)
  • 确保List的selection绑定到单选状态变量

修改后的完整代码

struct ContentView: View {        
    // 改用单选的可选整数类型,初始值设为0以选中首项
    @State var selection: Int? = 0
        
    var body: some View {
        NavigationView {
            List(selection: $selection) {
                NavigationLink(destination: TasksView(byPriotity: 3)) {
                    Label("All Tasks", systemImage: "largecircle.fill.circle")
                }.tag(0)
                
                Divider()
                
                NavigationLink(destination: TasksView(byPriotity: 0)) {
                    Label("Today", systemImage: "calendar")
                }.tag(1) // 添加对应tag
                
                NavigationLink(destination: TasksView(byPriotity: 1)) {
                    Label("Tomorrow", systemImage: "star.fill")
                }.tag(2) // 添加对应tag
             
            }
            .listStyle(SidebarListStyle())
            .frame(minWidth: 150, idealWidth: 150, maxWidth: .infinity, maxHeight: .infinity)
            
            // 根据选中的tag动态加载对应视图,替代原固定默认视图
            if let selection = selection {
                switch selection {
                case 0:
                    TasksView(byPriotity: 3)
                case 1:
                    TasksView(byPriotity: 0)
                case 2:
                    TasksView(byPriotity: 1)
                default:
                    TasksView(byPriotity: 3)
                }
            } else {
                TasksView(byPriotity: 3)
            }
        }
        .onAppear {
            // 强制视图加载时选中首项,避免Ventura下初始值不生效的情况
            selection = 0
        }
    }
}

额外说明

  • 未添加tag的NavigationLink无法被正确选中和触发视图切换,因此必须为所有可选项补全tag
  • 将右侧视图改为动态渲染,能实现侧边栏选择与内容视图的联动,更符合NavigationView的设计逻辑
  • 若你的场景确实需要多选,可保留Set<Int>类型,但需在.onAppear中手动设置selection = [0],同时确保所有可选项都有tag,不过侧边栏通常为单选场景,因此更推荐使用Int?的方案

内容的提问来源于stack exchange,提问作者Aleph

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 11:45:38