【问题标题】:Delete Core Data Row When Long Pressing长按删除核心数据行
【发布时间】:2021-07-07 00:51:51
【问题描述】:

我创建了一个新的带有核心数据的 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[$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)")
        }
    }

但我收到以下错误

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

【问题讨论】:

    标签: swiftui swiftui-list


    【解决方案1】:

    “.onDelete(执行操作:((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)")
        }
      }
    }
    

    【讨论】:

    • 我试过了,但我收到以下错误Value of type 'FetchedResults<item>' has no member 'remove'
    • 这只是一个例子,因为您没有向我们展示商品代码。您必须根据您的特定情况对其进行调整。可能在一个或多个项目上使用“viewContext.delete”。
    • 我已经通过猜测项目是什么来更新答案。
    • 非常感谢!我设法让它工作:)
    猜你喜欢
    • 1970-01-01
    • 2017-03-20
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多