Skip to content

Instantly share code, notes, and snippets.

@swillits
Last active September 13, 2015 17:14
Show Gist options
  • Save swillits/cda5bfc2269eb8d709f6 to your computer and use it in GitHub Desktop.
Save swillits/cda5bfc2269eb8d709f6 to your computer and use it in GitHub Desktop.
Animated moving tables view rows while sorting
[itemsTableView beginUpdates];
double t = [NSDate timeIntervalSinceReferenceDate];
NSArray * oldArrangement = [[self.itemsArrayController.arrangedObjects copy] autorelease];
NSArray * newArrangement = nil;
NSUInteger count = oldArrangement.count;
// "live" indexes of where final objects are currently.
NSUInteger * liveIndexes = calloc(sizeof(NSUInteger), oldArrangement.count);
self.itemsArrayController.sortDescriptors = itemsTableView.sortDescriptors;
newArrangement = self.itemsArrayController.arrangedObjects;
[newArrangement enumerateObjectsUsingBlock:^(id obj, NSUInteger finalIndex, BOOL *stop) {
liveIndexes[finalIndex] = [oldArrangement indexOfObject:obj];
}];
[newArrangement enumerateObjectsUsingBlock:^(id obj, NSUInteger finalIndex, BOOL *stop) {
NSUInteger liveIndex = liveIndexes[finalIndex];
// liveIndex will ALWAYS be >= finalIndex since we're "building the final array" starting at item 0 and moving forward, plucking from after the current index.
// When we pluck from n+x and move it n, all indexes of objects from n to n+x move to +1 higher index, so do that...
if (liveIndex != finalIndex) {
NSUInteger numToInc = (liveIndex - finalIndex);
for (NSUInteger i = 0; i < count && numToInc != 0; i++) {
if (liveIndexes[i] >= finalIndex && liveIndexes[i] < liveIndex) {
liveIndexes[i]++;
numToInc--;
}
}
// printf("%d to %d\n", (int)liveIndex, (int)finalIndex);
[itemsTableView moveRowAtIndex:liveIndex toIndex:finalIndex];
// Update with its new location
liveIndexes[finalIndex] = finalIndex;
}
}];
free(liveIndexes);
NSLog(@"%f", [NSDate timeIntervalSinceReferenceDate] - t);
[itemsTableView endUpdates];e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment