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:
- I have a list with 10 items.
- Select the 5. item.
- Remove an item below the 5. item, e.g. 7. item (right-click > "Delete")
- The 5. item stays selected.
Scenario 2:
- I have a list with 10 items.
- Select the 5. item.
- Remove an item above the 5. item, e.g. 3. item.
- 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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…