Skip to content

Instantly share code, notes, and snippets.

@zpasternack
Last active October 21, 2018 01:09
Show Gist options
  • Save zpasternack/a8724c31858133873215 to your computer and use it in GitHub Desktop.
Save zpasternack/a8724c31858133873215 to your computer and use it in GitHub Desktop.
Category on NSTableView for animating rows, using old and new sorted arrays as input. Updated to support items having been removed or added.
@implementation NSTableView (Reordering)
- (void) moveRowsWithOldObjects:(NSArray*)oldObjects newObjects:(NSArray*)newObjects
{
NSMutableArray* oldSortedArray = [oldObjects mutableCopy];
NSArray* newSortedArray = newObjects;
[self beginUpdates];
[newSortedArray enumerateObjectsUsingBlock:^(id obj, NSUInteger newIndex, BOOL *stop) {
NSUInteger oldIndex = [oldSortedArray indexOfObject:obj];
if( newIndex != oldIndex ) {
if( oldIndex == NSNotFound ) {
[oldSortedArray insertObject:obj atIndex:newIndex];
[self insertRowsAtIndexes:[NSIndexSet indexSetWithIndex:newIndex]
withAnimation:NSTableViewAnimationEffectFade | NSTableViewAnimationSlideLeft];
}
else {
[oldSortedArray removeObjectAtIndex:oldIndex];
[oldSortedArray insertObject:obj atIndex:newIndex];
[self moveRowAtIndex:oldIndex toIndex:newIndex];
}
}
}];
[oldSortedArray enumerateObjectsWithOptions:NSEnumerationReverse
usingBlock:^(id obj, NSUInteger oldIndex, BOOL *stop) {
NSUInteger newIndex = [newSortedArray indexOfObject:obj];
if( newIndex == NSNotFound ) {
[oldSortedArray removeObject:obj];
[self removeRowsAtIndexes:[NSIndexSet indexSetWithIndex:oldIndex]
withAnimation:NSTableViewAnimationEffectFade | NSTableViewAnimationSlideRight];
}
}];
[self endUpdates];
}
@end
@zpasternack
Copy link
Author

One might call it thusly:

NSArray* oldSortedArray = self.dataSource.arrangedObjects;
[self.dataSource arrangeObjects];
NSArray* newSortedArray = self.dataSource.arrangedObjects;
[self.tableView moveRowsWithOldObjects:oldSortedArray newObjects:newSortedArray];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment