macos - 在 macOS 上的 SwiftUI 列表视图中选择和删除核心数据实体
问题描述
我是 SwiftUI 的新手,但取得了合理的进展。我正在使用最新版本的 Xcode 12.4 并运行 BigSur 11.2.1。我正处于想要使用核心数据的阶段,但遇到了我找不到修复的问题。
当我创建基本 Xcode 项目时,我选择 App 和 macOS 作为模板然后我选择 Interface - SwiftUI、Life Cycle - SwiftUI App、Language - Swift 并选择 Use Core Data
一个新项目被创建并且构建和运行没有任何问题。在出现的窗口中,我只需单击顶部栏上的 + 按钮即可添加新项目(日期戳)。到现在为止还挺好。这都是香草苹果代码。
我被卡住的地方:- List - ContentView 中的 ForEach 视图不允许通过单击选择任何实体(项目),因此我找不到删除条目的方法。
如果我用一组文本项替换实体,那么我可以选择它们并通过使用 @State var selectKeeper = Set() 和一个选择来删除它们:列表视图中的 $selectKeeper。
有人可以解释一下怎么做吗?
这是内容视图的原始代码。
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
var body: some View {
List {
ForEach(items) { item in
Text("Item at \(item.timestamp!, formatter: itemFormatter)")
}
.onDelete(perform: deleteItems)
}
.toolbar {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
private func addItem() {
withAnimation {
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { items[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
private let itemFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .medium
return formatter
}()
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}
解决方案
您应该添加EditButton()并可能将所有这些都包装在 NavitagionView 中,这可能会为您提供所需的内容:
var body: some View {
NavigationView{
List {
ForEach(items) { item in
Text("Item at \(item.timestamp!, formatter: itemFormatter)")
}
.onDelete(perform: deleteItems)
}
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
#if os(iOS)
EditButton()
#endif
}
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
}
}
推荐阅读
- sqlite - sqlite 计入列
- tensorflow - 使用 tfds.features 构造的特征解析 tfrecord
- ruby - 从 ruby 中的 CSV 文件中获取数据并在 DESC 中排序数据?
- javascript - 我应该在哪里实现带有分页的 for 循环?
- drake - 在 Drake 中模拟 MultiBodyPlant 时是否可以绕过 SpatialInertia?
- php - 如何使用加载更多按钮而不是分页来显示产品。任何想法?
- javascript - 无效合并运算符不工作或未启用?
- sql - 如何使用oracle sql将所有表从一个数据库复制到另一个数据库
- java - 无法为 Android 构建测试 DPC
- python - 为 python 3.9 构建一个 uwsgi 插件失败,它适用于旧版本。还有其他选择吗?