Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView animate row reordering upon sort

I have a table that users can sort in two different ways. When users change between these two sorting modes, I want the re-sort to be animated. And while UITableView's methods provide animation help for inserting, deleting, and reloading rows, I don't see anything that lets me animate row movement.

Am I missing something?

Assuming I'm not, does anyone have any sample code on how to do this?

Thanks.

like image 909
Greg Maletic Avatar asked Feb 21 '11 21:02

Greg Maletic


2 Answers

I know this is an older question, but I ran into the same issue and think I found a solution, so I thought I'd share in case anyone else finds their way here with the same question. I'm also not sure how great of a solution it is, but it seems to work for me.

My TableView gets its data from an array called _objects. In my method for sorting, I begin by creating another array which is an exact copy of the data array:

    NSArray *objectsBeforeSort = [NSArray arrayWithArray:_objects];

I then sort my data array, _objects, using sort descriptors that I had already created. After calling the appropriate sort method on my array, I use this to animate the table update:

[self.tableView beginUpdates];

for (int i = 0; i < _objects.count; i++)
{
    // newRow will get the new row of an object.  i is the old row.
    int newRow = [_objects indexOfObject:objectsBeforeSort[i]];
    [self.tableView moveRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] toIndexPath:[NSIndexPath indexPathForRow:newRow inSection:0]];
}


[self.tableView endUpdates];

I haven't tested this code extensively yet, but it appears to give the desired result.

like image 76
tjf Avatar answered Oct 16 '22 18:10

tjf


Have you tried using moveRowAtIndexPath:toIndexPath: inside a beginUpdates-endUpdates block? It seems to be what the developer docs are currently recommending. If that doesn't work on its own you could also try wrapping it in a [UIView animateWithDuration:animations:] block.

Link to the ADC documentation for UITableView: https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UITableView_Class/Reference/Reference.html#//apple_ref/doc/c_ref/UITableView

like image 29
Julian Avatar answered Oct 16 '22 18:10

Julian