2

I'm building a macOS swiftUI app with a sidebar navigationView that determines what displays on the right of the screen. The user is able to move around the items in the sidebar. However when an item is dragged to a new location, the selection in the navigationView is removed. I was wondering how I could keep the same item selected after one is moved, even if the one being moved in the one selected.

This is my code for the NavigationView:

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]
    }
}

And here's my move() function:

private func move(from source: IndexSet, to destination: Int) {
    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()
    } catch {
        let nsError = error as NSError
        fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
    }
}

I'm not sure why this causes the selectedInstance to turn to nil, and I've tried saving the index of the selectedInstance and calculating what it should be after moving the item, but I haven't had any luck with this. So what would be the say to preserve the selected sidebar item?

Thanks!

Cameron Delong
  • 454
  • 1
  • 6
  • 12

0 Answers0