Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView delete and reload cells

I am delete some rows in UITableView like this:

[tableView deleteRowsAtIndexPaths:toDelete withRowAnimation:UITableViewRowAnimationAutomatic];

This adds a nice animation to the delete operation.

However, after deleting I need to update all the currently visible rows. Calling

[tableView reloadData];

right after the first call works, but the nice animation effect is gone. What's a better way to do this? i.e., to animate the delete operation, and update all the currently visible rows? Thanks!

The reason why I need to do this is because each cell contains a 'checkbox'. My view controller is checkbox's delegate and each checkbox has an NSIndexPath associated with it. When the checkbox is toggled, delegate is called telling it hey we toggled for x index path. Now, if some rows are deleted, the index paths need to be update. That's why I need to reload everything so each checkbox knows where it belongs.

like image 705
0xSina Avatar asked Oct 07 '22 18:10

0xSina


1 Answers

In your deletion action use the performBatchUpdates instead of [tableView beginUpdates] this allows you to have a completion block

Animates multiple insert, delete, reload, and move operations as a group.

self.tableView.performBatchUpdates({
     //do stuff then delete the row
     self.tableView.deleteRows(at: [indexPath], with: .fade)
}, completion: { (done) in
     //perform table refresh
     self.tableView.reloadData()

})
like image 114
Entrabiter Avatar answered Oct 13 '22 09:10

Entrabiter