长按删除核心数据行

Delete Core Data Row When Long Pressing

我创建了一个包含核心数据的新 Mac OS xcode 应用程序,并且正在尝试生成允许您添加项目的默认代码。

但我想更改删除行的方式。使用长按手势触发删除。

查看:

var body: some View {
    List {
        ForEach(items) { item in
            Text("Item at \(item.timestamp!, formatter: itemFormatter)")
                
        }
        //.onDelete(perform: deleteItems) Want to change this command to the one below
          .onLongPressGesture(minimumDuration: 1.5, perform: deleteItems)

    }
    .toolbar {
        Button(action: addItem) {
            Label("Add Item", systemImage: "plus")
        }
    }
}

删除项目功能

private func deleteItems(offsets: IndexSet) {
    withAnimation {
        offsets.map { items[[=11=]] }.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)")
        }
    }

但是我得到以下错误

Cannot convert value of type '(IndexSet) -> ()' to expected argument type '() -> Void'

".onDelete(执行操作:((IndexSet) -> Void)?)" 和 “.onLongPressGesture(minimumDuration: Double = 1.5, perform action: @escaping () -> Void)” 如您所见,具有不同的签名。所以你所做的是行不通的。

您可以尝试这样的操作:

List {
    ForEach(items, id: \.self) { item in
        Text("Item at \(item)")
            .onLongPressGesture(minimumDuration: 1.5, perform: {deleteItems2(item)})
    }
   // .onDelete(perform: deleteItems)
}
    
private func deleteItems2(_ item: Item) {
    if let ndx = items.firstIndex(of: item) {
        viewContext.delete(items[ndx])
    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)")
    }
  }
}