1

我正在尝试使用上下文菜单删除列表项。数据是从核心数据中获取的。

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

1 回答 1

1

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

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

关于你的最后一个问题:

我也想知道为什么我在使用 .onDelete 时不需要指定 IndexSet

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

于 2022-01-12T19:24:47.420 回答