You need to enable JavaScript to run this app. SwiftUI macOS应用侧边栏NavigationView拖动排序后如何保留选中项
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI macOS应用侧边栏NavigationView拖动排序后如何保留选中项

问题根因

你的代码存在两个导致选中状态丢失的问题:

  1. 你给InstanceRow手动加了.id(UUID())修饰符,每次列表刷新时所有行的ID都会随机变化,SwiftUI会将所有行识别为全新视图,原本的选中tag无法匹配到对应视图,直接导致选中状态清空。
  2. 拖拽排序后Core Data保存操作会触发列表数据源刷新,没有主动保留当前选中的实例,也可能导致选中状态丢失。

修复步骤

  1. 移除InstanceRow后的.id(UUID())修饰符,只要你的Instance实体遵守Identifiable协议,ForEach会自动使用实例的唯一ID做标识,不需要手动设置随机ID:
NavigationView {
    List() {
        ForEach(instances) { instance in
            NavigationLink(destination: InstanceView(instance: instance), tag: instance, selection: $selectedInstance) {
                InstanceRow(instance: instance)
                // 移除原有.id(UUID())代码
            }
        }
         .onMove(perform: move)
    }
    .listStyle(SidebarListStyle())
    .navigationTitle("Instances")
    .frame(minWidth: 150)
    .toolbar {
        ToolbarItem {
            Button(action: toggleSidebar, label: {
                Image(systemName: "sidebar.left")
            })
        }
    }
    .onAppear {
        selectedInstance = instances[0]
    }
}
  1. 在move函数中增加选中状态的保存和恢复逻辑,拖拽操作完成后重新赋值选中实例:
private func move(from source: IndexSet, to destination: Int) {
    // 先保存当前选中的实例
    let currentSelected = selectedInstance
    
    var revisedItems: [Instance] = instances.map{$0}
    revisedItems.move(fromOffsets: source, toOffset: destination)
        
    for reverseIndex in stride(from: revisedItems.count - 1, through: 0, by: -1) {
        revisedItems[reverseIndex].userOrder = Int16(reverseIndex)
    }
        
    do {
        try viewContext.save()
        // 保存成功后恢复选中状态
        selectedInstance = currentSelected
    } catch {
        let nsError = error as NSError
        fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
    }
}

注意事项

  • 确保你的Instance实体遵守Hashable协议(NSManagedObject子类默认满足该要求,无需额外修改),才能正常作为NavigationLink的tag使用。
  • 确认你的instances数组的排序规则是按userOrder升序排列,保证Core Data保存后列表顺序和拖拽后的顺序一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 04:15:03