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

NavigationStack列表选中项重启后仅高亮未跳转对应视图问题

问题原因及解决方案

你遇到的问题核心是:List的selection仅负责UI上的选中高亮,不会主动触发NavigationLink的导航动作。NavigationStack的导航状态是由其path属性控制的,仅靠保存选中索引无法自动恢复之前的导航层级。

修改方案

改用NavigationStack的路径绑定来同步导航状态,同时关联@AppStorage保存的选中索引,代码示例如下:

@AppStorage("selectedIndex") private var selectedIndex: Int?
@State private var navigationPath: [Int] = []

var body: some View {
    NavigationStack(path: $navigationPath) {
        List(selection: $selectedIndex) {
            ForEach(0..<myObjectsArray.count, id: \.self) { index in
                NavigationLink(value: index) {
                    VStack(alignment: .leading) {
                        HStack{
                            Text(myObjectsArray[index].name)
                            Text("- \(myObjectsArray[index].numbers) Employees")
                        }
                        Text("last Update: \(myObjectsArray[index].updated.ISO8601Format())")
                            .font(.footnote)
                    }
                }
            }
        }
        .navigationDestination(for: Int.self) { index in
            MyObjectView(selectedObject: myObjectsArray[index])
        }
        .onAppear {
            // 启动时同步保存的索引到导航路径
            if let index = selectedIndex, navigationPath.isEmpty {
                navigationPath.append(index)
            }
        }
        .onChange(of: navigationPath) { newPath in
            // 导航变化时更新保存的选中索引
            selectedIndex = newPath.last
        }
    }
}

关键说明

  1. 路径绑定:通过NavigationStack(path: $navigationPath)管理导航栈,路径数组中的元素对应导航层级
  2. 导航目标关联:用navigationDestination替代原NavigationLink的destination参数,建立路径值与目标视图的映射
  3. 状态同步:
    • onAppear在启动时将保存的selectedIndex同步到路径,触发自动导航
    • onChange监听路径变化,实时更新@AppStorage中的索引,保证重启后状态一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 15:15:01