Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

swift - Keep current selection when deleting an item from the list

I have a list that displays navigation links. Users are able to add and remove elements to the list. When an element is removed, the selected navigation link should stay selected.

Below is my view, which partially works.

Scenario 1:

  1. I have a list with 10 items.
  2. Select the 5. item.
  3. Remove an item below the 5. item, e.g. 7. item (right-click > "Delete")
  4. The 5. item stays selected.

Scenario 2:

  1. I have a list with 10 items.
  2. Select the 5. item.
  3. Remove an item above the 5. item, e.g. 3. item.
  4. No item is selected

I've printed out the selectedItemId after removing an item and it's correctly set. Any ideas as to why this is happening?

import CoreData
import SwiftUI

struct Sidebar: View {
    @Environment(.managedObjectContext)
    private var viewContext
    
    @FetchRequest(entity: Element.entity(), sortDescriptors: [NSSortDescriptor(keyPath: Element.title, ascending: false)])
    private var elements: FetchedResults<Element>
    
    @AppStorage("SelectedElementId")
    var selectedElementId: String?
    
    var body: some View {
        VStack(alignment: .leading) {
            List(selection: self.$selectedElementId) {
                ForEach(self.elements) { element in
                    NavigationLink(destination: ContentView(), tag: element.id!, selection: self.$selectedElementId) {
                        Text(element.title!)
                    }
                    .contextMenu {
                        Button(action: {
                            self.deleteElement(element)
                        }) {
                            Text("Delete")
                        }
                    }
                }
            }.listStyle(SidebarListStyle())
            
            Button(action: addElement) {
                HStack {
                    Text("Add element")
                }
            }
        }
    }
    
    private func addElement() {
        let element = Element(context: viewContext)
        element.id = UUID().uuidString
        element.title = "My title"
        
        self.selectedElementId = element.id
               
        do {
            try self.viewContext.save()
        } catch {
            let nsError = error as NSError
            fatalError("Unresolved error (nsError), (nsError.userInfo)")
        }
    }
    
    private func deleteElement(_ elementForDeletion: Element) {
        var selectedElementId = self.selectedElementId
        
        print("Currently selected", selectedElementId)
                
        var i = self.elements.startIndex
        let count = self.elements.count
                
        if count == 1 {
            selectedElementId = nil
        } else {
            while selectedElementId == elementForDeletion.id, i < count {
                selectedElementId = self.elements[i].id
                i += 1
            }
        }
                
        do {
            self.viewContext.delete(elementForDeletion)
                   
            try self.viewContext.save()
        } catch {
            let nsError = error as NSError
            fatalError("Unresolved error (nsError), (nsError.userInfo)")
        }
                
        self.selectedElementId = selectedElementId
        
        print("New/old selection", selectedElementId)
    }
}
question from:https://stackoverflow.com/questions/65863140/keep-current-selection-when-deleting-an-item-from-the-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...