目標
我想從一個洗掉一個專案SectionedFetchRequest上的ForEach內部串列。我找到的唯一解決方案是FetchRequest我設法從 UIList 中洗掉它,但沒有從 CoreData 的ViewContext.
我的問題是獨一無二的,因為我試圖從與 FetchRequest 不同的 SectionedFetchRequest 中洗掉
@SectionedFetchRequest(entity: Todo.entity(), sectionIdentifier: \.dueDateRelative, sortDescriptors: [NSSortDescriptor(keyPath: \Todo.dueDate, ascending: true)], predicate: nil, animation: Animation.linear)
var sections: SectionedFetchResults<String, Todo>
var body: some View {
NavigationView {
List {
ForEach(sections) { section in
Section(header: Text(section.id.description)) {
ForEach(section) { todo in
TodoRowView(todo: todo)
.frame(maxWidth: .infinity)
.listRowSeparator(.hidden)
}
.onDelete { row in
deleteTodo(section: section.id.description, row: row)
}
}
}
}
func deleteTodo(section: String, row: IndexSet) {
// Need to delete from list and CoreData viewContex.
}
// My old way of deleting notes with a regular fetch Request
func deleteNote(at offsets: IndexSet) {
for index in offsets {
let todo = todos[index]
viewContext.delete(todo)
}
try? viewContext.save()
}
uj5u.com熱心網友回復:
這就是您將如何使用鏈接...
將此添加到 TodoRowView(todo: todo)
.swipeActions(content: {
Button(role: .destructive, action: {
deleteTodo(todo: todo)
}, label: {
Image(systemName: "trash")
})
})
你需要這個方法 View
public func deleteTodo(todo: Todo){
viewContext.delete(todo)
do{
try viewContext.save()
} catch{
print(error)
}
}
或者你也可以使用使用當前設定onDelete的ForEach
.onDelete { indexSet in
deleteTodo(section: Array(section), offsets: indexSet)
}
使用這種方法的
func deleteTodo(section: [Todo], offsets: IndexSet) {
for index in offsets {
let todo = section[index]
viewContext.delete(todo)
}
try? viewContext.save()
}
當然,要使其中任何一項作業,您都需要一個作業
@Environment(\.managedObjectContext) var viewContext
在檔案頂部
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/384664.html
