代码之家  ›  专栏  ›  技术社区  ›  forrest

从TableView中删除行的正确方法是什么?

  •  0
  • forrest  · 技术社区  · 7 年前

    在xcode 9中,我有一个tableview,其中包含从coredata中提取的数据列表。数据的添加、编辑和保存工作正常,但当我试图删除数据时,我遇到了一个两难的境地,一个是美观的,另一个是崩溃的应用程序。

    如果我使用以下代码,它将从CoreData和TableView中删除数据,但不使用.fade选项。它只是从桌面上消失了。

      override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
             context.delete(tasks[indexPath.row])
             tasks.remove(at: indexPath.row)
             saveTasks()
      }
    

    如果我使用以下选项,应用程序将崩溃。

      override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
             context.delete(tasks[indexPath.row])
             tableView.deleteRows(at: [indexPath], with: .fade)
             saveTasks()
      }
    

    如何将.fade选项应用于位于的移除?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Daniel    7 年前

    您需要将这两种解决方案结合起来:

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        context.delete(tasks[indexPath.row])
        tasks.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
        saveTasks()
    }
    

    基本上,你们都必须更新数据( tasks )告诉我 tableView 重新加载。

    推荐文章