我是SwiftUI的新手,但取得了合理的进展。我使用的是最新版本的Xcode 12.4,运行的是BigSur 11.2.1。我正处于我想使用核心数据的阶段,但遇到了一个我找不到修复的问题。
当我创建基本的Xcode项目时,我选择App和macOS作为模板然后我选择接口- SwiftUI,生命周期- SwiftUI App,语言- Swift并选择使用Core Data
一个新项目被创建,构建和运行没有任何问题。在出现的窗口中,我可以添加一个新项目(一个日期戳),只需点击顶部栏上的+按钮。到目前为止一切顺利。这是所有的香草苹果代码。
我卡住的地方:-在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")
}
}
}
}
}