我正在尝试使用上下文菜单删除列表项。数据是从核心数据中获取的。
.onDelete 与我的 deleteExercise 函数按预期工作,无需进一步操作。但是当在上下文菜单按钮中调用 deleteExercise 时,它会询问我真的不知道从哪里得到的 IndexSet。
我也想知道为什么我在使用 .onDelete 时不需要指定 IndexSet
struct ExercisesView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)],
animation: .default)
private var exercises: FetchedResults<Exercise>
var body: some View {
NavigationView {
List {
ForEach(exercises) { e in
VStack {
NavigationLink {
ExerciseDetailView(exercise: e)
} label: {
Text(e.name ?? "")
}
}
.contextMenu { Button(role: .destructive, action: { deleteExercise(offsets: /* Index Set */) }) {
Label("Delete Exercise", systemImage: "trash")
} }
}
.onDelete(perform: deleteExercise)
}
}
}
private func deleteExercise(offsets: IndexSet) {
withAnimation {
for index in offsets {
let exercise = exercises[index]
viewContext.delete(exercise)
}
viewContext.save()
}
}
}