首页 > 解决方案 > 使用 Core Data 删除可滑动的 TableView 单元格

问题描述

因此,我可以添加任务并将这些任务保留在我的应用程序中。现在我想做的是能够删除任务并保留我删除的内容。我正在使用可滑动单元可可豆荚,以允许用户向左滑动并删除项目。但是,我下面的代码似乎并没有按照我想要的方式运行。首先,滑动手势不起作用,其次,如果我有“task1”、“task2”、“task3”,我无法删除任务 3,但我可以删除任务 1,然后我可以删除任务 3。此外,有时我删除的项目是持久的,有时不是。我的代码如下,非常感谢任何帮助。

class DailyTasksTableViewController: UITableViewController {

//Variables
var tasksArray = [Task]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
.....

extension DailyTasksTableViewController: SwipeTableViewCellDelegate {
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
        guard orientation == .right else { return nil }

    let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in
        self.context.delete(self.tasksArray[indexPath.row])
        self.tasksArray.remove(at: indexPath.row)

        do {
            try self.context.save() 
        }catch{
            print("error saving delete \(error)")
        }
    }

    // customize the action appearance
    deleteAction.image = UIImage(named: "delete-icon")

    return [deleteAction]
}

func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions {
    var options = SwipeOptions()
    options.expansionStyle = .destructive
    return options
}

}

标签: iosswiftuitableviewcore-dataxcode9.3

解决方案


“首先,滑动手势不起作用”的答案

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

推荐阅读