Jus*_*ock 8 iphone core-data ios swift swiftui
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>
Run Code Online (Sandbox Code Playgroud)
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)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
func deleteTodo(section: String, row: IndexSet) {
// Need to delete from list and CoreData viewContex.
}
Run Code Online (Sandbox Code Playgroud)
// 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()
}
Run Code Online (Sandbox Code Playgroud)
lor*_*sum 17
这就是您使用该链接的方式...
将其添加到TodoRowView(todo: todo)
.swipeActions(content: {
Button(role: .destructive, action: {
deleteTodo(todo: todo)
}, label: {
Image(systemName: "trash")
})
})
Run Code Online (Sandbox Code Playgroud)
你需要这个方法View
public func deleteTodo(todo: Todo){
viewContext.delete(todo)
do{
try viewContext.save()
} catch{
print(error)
}
}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用当前的onDelete
设置ForEach
.onDelete { indexSet in
deleteTodo(section: Array(section), offsets: indexSet)
}
Run Code Online (Sandbox Code Playgroud)
就是用这个方法
func deleteTodo(section: [Todo], offsets: IndexSet) {
for index in offsets {
let todo = section[index]
viewContext.delete(todo)
}
try? viewContext.save()
}
Run Code Online (Sandbox Code Playgroud)
当然,要使这一切发挥作用,您需要一个有效的
@Environment(\.managedObjectContext) var viewContext
Run Code Online (Sandbox Code Playgroud)
在文件的顶部
归档时间: |
|
查看次数: |
1999 次 |
最近记录: |