简体   繁体   English

使用核心数据删除可滑动滑动的TableView单元格

[英]Deleting swipe-able TableView Cells using Core Data

So, I can add tasks and persist those tasks in my app. 因此,我可以添加任务并将这些任务保留在我的应用程序中。 Now what I would like to do is be able to delete tasks and persist what I deleted. 现在,我想做的是能够删除任务并保留我删除的内容。 I am using the swipeable cell cocoa pod in order to allow the user to swipe to the left and delete items. 我正在使用可滑动滑动单元可可豆荚,以便允许用户向左滑动并删除项目。 However, my code below doesn't seem to function the way I want it to. 但是,下面的代码似乎并没有达到我想要的功能。 First of, the swipe gesture isn't working and secondly if I had "task1", "task2", "task3", I can't delete task 3 but I can delete task 1 then I can delete task 3. Also, sometimes my deleted item is persisted and sometimes not. 首先,滑动手势不起作用,其次,如果我有“ task1”,“ task2”,“ task3”,则无法删除任务3,但可以删除任务1,然后可以删除任务3。此外,有时我删除的项目仍然存在,有时却没有。 My code is below, any help is greatly appreciated. 我的代码在下面,非常感谢您的帮助。

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
}

}

The answer for "First of, the swipe gesture isn't working" 答案为“首先,滑动手势不起作用”

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM