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

What is the correct way to remove a row from a tableView?

在 Xcode9 中,我有一个 tableView,其中包含从 CoreData 中提取的数据列表。数据的添加、编辑和保存工作正常,但当我尝试删除数据时,我遇到了一个两难困境,一方面是审美问题,另一方面是应用程序崩溃。

如果我使用以下代码,它会从 CoreData 和 tableview 中删除数据,但没有 .fade 选项。它就从 tableView 中消失了。

  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 选项应用到移除位置:?

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

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 重新加载。