从Swift中的UITableView中删除一个单元格

时间:2015-12-22 03:58:44

标签: ios swift uitableview swift2

从tableView中删除单元格时,动画运行正常,但不会重新加载tableView数据。我尝试在没有.beginUpdates().endUpdates()的情况下运行,而是使用.reloadData(),并且该过程有效,但动画无效。

    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    switch editingStyle {
    case .Delete:
        // remove the deleted item from the model
        let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let context:NSManagedObjectContext = appDel.managedObjectContext
        context.deleteObject(coreData[indexPath.row] as NSManagedObject)
        coreData.removeAtIndex(indexPath.row)
        do {
            try context.save()
        } catch {
            print("Error deleting NSManagedObject")
        }


        tableView.beginUpdates()
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        tasks.removeAtIndex(indexPath.row)
        names.removeAtIndex(indexPath.row)
        ids.removeAtIndex(indexPath.row)
        tableView.endUpdates()
        // remove the deleted item from the `UITableView`

    default:
        return

    }

}

顺便说一下,tasks数组是tableView的主要数据。

如何在删除单元格时重新加载数据,使用平滑删除动画?

2 个答案:

答案 0 :(得分:4)

需要考虑两件事:

  1. 您必须在更新表视图之前更新数据模型。因此,代码的顺序必须是:

    tasks.removeAtIndex(indexPath.row)
    names.removeAtIndex(indexPath.row)
    ids.removeAtIndex(indexPath.row)
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    
  2. 由于您只需拨打一次电话即可更新表格视图,因此无需拨打begin/endUpdates

答案 1 :(得分:2)

removeAtIndex...之前移动所有beginUpdates行,你必须首先从数据中删除对象,然后才能删除行