长按删除核心数据行

问题描述

我使用核心数据创建了一个新的 Mac OS xcode 应用程序,并使用代码生成允许您添加项目。

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

查看:

getBatchLog() {
    isFound=false
    tac test.log | while read -r line; do
        if [[ condition ]]; then
            isFound=true
            return 0
        fi
   
    done
    if [[ "${isFound}" == true ]]; then #isFound not change outside the loop,it is always false
      echo "found "
    else 
      echo "not found"
    fi
}

删除项目功能

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")
        }
    }
}

但我收到以下错误

无法将类型 '(IndexSet) -> ()' 的值转换为预期的参数类型 '() -> Void'

解决方法

".onDelete(perform action: ((IndexSet) -> Void)?)" 和 “.onLongPressGesture(minimumDuration: Double = 1.5,执行动作:@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)")
    }
  }
}