SwiftUI、核心数据-使用上下文菜单删除列表项 [英] SwiftUI, Core Data - Delete List Item with Context Menu
本文介绍了SwiftUI、核心数据-使用上下文菜单删除列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用上下文菜单删除列表项。 数据从核心数据中提取。
.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()
}
}
}
推荐答案
您可以创建单独的Delete方法,而不是尝试从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()
}
}
关于您的最后一个问题:
我还想知道为什么在使用.onDelete时不需要指定IndexSet
您不需要指定它,因为它是由onDelete
作为参数发送的--这是您的deleteExercise(offsets:)
从onDelete
修饰符接收的内容。
这篇关于SwiftUI、核心数据-使用上下文菜单删除列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文