Skip to content

Instantly share code, notes, and snippets.

@harrisg
Forked from zpasternack/NSTableView+Reordering.m
Created January 27, 2016 15:32
Show Gist options
  • Save harrisg/ec6e7d99912228b8d3f0 to your computer and use it in GitHub Desktop.
Save harrisg/ec6e7d99912228b8d3f0 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment