[英]Deleting a cell from UITableView in Swift
When deleting a cell from the tableView, the animation runs fine, but the tableView data isn't reloaded. 从tableView删除单元格时,动画运行良好,但不会重新加载tableView数据。 I tried running without
.beginUpdates()
and .endUpdates()
and instead used .reloadData()
, and the process worked but the animation didn't work. 我尝试在没有
.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
}
}
By the way, the tasks
array is the the main data for the tableView. 顺便说一下,
tasks
数组是tableView的主要数据。
How can I reload the data as I delete a cell, WITH the smooth deletion animation? 如何使用平滑删除动画在删除单元格时重新加载数据?
Two things to consider: 要考虑的两件事:
You must update the data model before you update the table view. 在更新表视图之前,必须先更新数据模型。 Therefore the order of the code must be:
因此,代码的顺序必须为:
tasks.removeAtIndex(indexPath.row) names.removeAtIndex(indexPath.row) ids.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
There is no need for the calls to begin/endUpdates
since you only make a single call to update the table view. 无需进行
begin/endUpdates
因为您只需进行一次调用即可更新表视图。
将所有removeAtIndex...
行移动到beginUpdates
之前,必须先从数据中删除对象,然后才能删除行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.