iOS:Tableview 开始更新从不播放动画 [英] iOS: Tableview Begin updates never plays animation
问题描述
当用户长按一个单元格并确认更改时,我编写了一些代码来从后端和本地数据存储中删除帖子.但是,tableview 不会更新.我断点了我的代码并且执行了 tableView 操作代码,为什么我的行没有从视图中删除?
I have written some code to delete a post from the back end and local data storage when a user long presses a cell and confirms the change. However the tableview does not update. I have breakpointed my code and the tableView manipulation code is executed, why is my row not being removed from the view?
let alertView = UIAlertController(title: "Really?", message: "Are you sure you want to delete this post? Once you do it will be gone forever.", preferredStyle: .Alert)
alertView.addAction(UIAlertAction(title: "Delete Post", style: UIAlertActionStyle.Default, handler: { (alertView:UIAlertAction!) -> Void in
let p = post.getRawPost()
p.deleteInBackgroundWithBlock({ (deleted:Bool, error:NSError?) -> Void in
// Remove from the local datastore too
p.fetchFromLocalDatastore()
p.deleteInBackgroundWithBlock({ (deleted:Bool, error:NSError?) -> Void in
// Update the table view
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
self.tableView.endUpdates()
})
})
}))
据我所知,beginUpdates
和 endUpdates
用于更新 tableView 的特定部分,而无需执行完整的 reloadData
调用来源.我在这里遗漏了什么吗?
As I understand it, beginUpdates
and endUpdates
is used to update specific sections of a tableView without needing to perform a full reloadData
call on the source. Am I missing something here?
UPDATE 我将 tableView 更新代码移动到主线程,每当调用 endUpdates
时都会导致崩溃.我的新代码如下所示,并在主线程上调用:
UPDATE I moved the tableView update code to the main thread, this produced a crash whenever endUpdates
is called. My new code looks as below, and is called on the main thread:
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: indexPath.row, inSection: indexPath.section)], withRowAnimation: UITableViewRowAnimation.Automatic)
self.tableView.endUpdates()
推荐答案
将下面的代码片段包裹在 MAIN THREAD 中:
Wrap the code snippet below in MAIN THREAD instead:
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
self.tableView.endUpdates()
<小时>
编辑崩溃
p.deleteInBackgroundWithBlock({ (deleted:Bool, error:NSError?) -> Void in
// Remove from the local datastore too
p.fetchFromLocalDatastore()
// Delete the desired item from array
...
// Remove cell that the item belong to animated in main thread
dispatch_async(dispatch_get_main_queue(), {
// Update the table view
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
})
})
这篇关于iOS:Tableview 开始更新从不播放动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!