Reload Table view cell with animation (Swift)

William Larson picture William Larson · Apr 14, 2015 · Viewed 28.6k times · Source

Is there a way to reload specific UITableView cells with multiple sections with animations?

I've been using:

self.TheTableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.Right)

This animates all the cells in the section though. The other option is to use:

self.TheTableView.reloadRowsAtIndexPaths(<#indexPaths: [AnyObject]#>, 
                                         withRowAnimation: <#UITableViewRowAnimation#>)

EDIT:

After using reloadRowsAtIndexPaths

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 1. The number of rows contained in an existing section after the update (5) must be equal to the number of rows contained in that section before the update (4), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

Trying to find a smooth way of reloading a tableview by appending objects into an array.

Calling TheTableView.reloadData() before reloadRowsAtIndexPaths works, but the animation is glitchy. Is there another approach?

Answer

Mark McCorkle picture Mark McCorkle · Apr 14, 2015

Why not just reload the cells directly? The indexPath contains the section and row so just keep track of which section you want to reload and fill the indexes in that array.

var indexPath1 = NSIndexPath(forRow: 1, inSection: 1)
var indexPath2 = NSIndexPath(forRow: 1, inSection: 2)
self.tableView.reloadRowsAtIndexPaths([indexPath1, indexPath2], withRowAnimation: UITableViewRowAnimation.Automatic)

Based on your comment you are looking to change your array and have the tableView animate in the changes. If that's the case you should consider using beginUpdates() and endUpdates() for UITableViews or even an NSFetchedResultsController so it handles all of the update animations cleanly.

self.tableView.beginUpdates()
// Insert or delete rows
self.tableView.endUpdates()

I'd recommend using NSFetchedResultsController if you're using Core Data as it simplifies this entire process. Otherwise you have to handle the changes yourself. In other words, if your array changes you need to manually remove or insert rows in the tableview using beginUpdates() and endUpdates(). If you aren't using Core Data, study this to grasp how it's all handled.