Skip to content

Instantly share code, notes, and snippets.

@mlaster
Last active October 5, 2015 09:07
Show Gist options
  • Save mlaster/2783845 to your computer and use it in GitHub Desktop.
Save mlaster/2783845 to your computer and use it in GitHub Desktop.
animating UITableView updates
- (void)animateUpdateFromOldList:(NSArray *)oldList newList:(NSArray *)newList {
NSMutableArray *workArray = [oldList mutableCopy];
NSMutableSet *oldSet = [[NSMutableSet alloc] initWithArray:oldList];
NSMutableSet *newSet = [[NSMutableSet alloc] initWithArray:newList];
NSMutableSet *deleteSet = nil;
NSMutableSet *insertSet = nil;
static NSInteger offset = 0;
deleteSet = [oldSet mutableCopy];
[deleteSet minusSet:newSet];
insertSet = [newSet mutableCopy];
[insertSet minusSet:oldSet];
NSLog(@"oldList.count: %d newList.count: %d", [oldList count], [newList count]);
[self.dynamicTableView beginUpdates];
// Process deletes
for (NSDictionary *deletedObject in deleteSet) {
NSUInteger index = [oldList indexOfObject:deletedObject];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(NSInteger)index + offset inSection:0];
[workArray removeObjectAtIndex:index];
NSLog(@"DELETE row at %@", [NSArray arrayWithObject:indexPath]);
[self.dynamicTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
// Process inserts
for (NSDictionary *insertObject in insertSet) {
NSUInteger index = [newList indexOfObject:insertObject];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(NSInteger)index + offset inSection:0];
NSLog(@"INSERT row at %@", [NSArray arrayWithObject:indexPath]);
[self.dynamicTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
// Process moves
for (NSUInteger i = 0; i < [newList count]; i++) {
NSDictionary *candidateObject = newList[i];
if ([deleteSet containsObject:candidateObject] == NO &&
[insertSet containsObject:candidateObject] == NO) {
NSUInteger oldIndex = [oldList indexOfObject:candidateObject];
NSUInteger newIndex = [newList indexOfObject:candidateObject];
NSIndexPath *oldIndexPath = [NSIndexPath indexPathForRow:(NSInteger)oldIndex + offset inSection:0];
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:(NSInteger)newIndex + offset inSection:0];
if (oldIndex != newIndex) {
NSLog(@"MOVE row at %@ to %@", oldIndexPath, newIndexPath);
[self.dynamicTableView moveRowAtIndexPath:oldIndexPath toIndexPath:newIndexPath];
}
}
}
[self.dynamicTableView endUpdates];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment