SwiftUI,Core Data - 使用上下文菜单删除列表项

SwiftUI, Core Data - Delete List Item with Context Menu

我正在尝试使用上下文菜单删除列表项。 数据取自核心数据。

.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()
            
        }
    }
    
}

您可以创建一个单独的删除方法,而不是尝试从 ForEach 派生一个 IndexSet,它不会立即为您公开一个:

.contextMenu { Button(role: .destructive, action: { 
  deleteExercise(exercise)
}) {
  Label("Delete Exercise", systemImage: "trash")
} }
func deleteExercise(_ exercise: Exercise) { //I'm making an assumption that your model is called Exercise
  withAnimation {
    viewContext.delete(exercise)
    viewContext.save() 
  }
}

关于你的最后一个问题:

I am also wondering why I don't need to specify the IndexSet when using .onDelete

您不需要指定它,因为它是由 onDelete 作为参数发送的——这就是您的 deleteExercise(offsets:)onDelete 修饰符接收的内容。