Re: Reordering a table insanity
Re: Reordering a table insanity
- Subject: Re: Reordering a table insanity
- From: Seth Willits <email@hidden>
- Date: Wed, 28 Nov 2012 09:13:33 -0800
By the way, the pseudo code I wrote does work…
NSIndexSet * draggedIndexes = ...;
NSMutableArray * newThings = [[self.things mutableCopy] autorelease];
NSArray * draggedObjects = [self.things objectsAtIndexes:draggedIndexes];
NSInteger numberOfRows = tableView.numberOfRows;
NSInteger dropIndex = row;
while ([draggedIndexes containsIndex:dropIndex] && dropIndex < numberOfRows) dropIndex++;
id beforeObject = (dropIndex == numberOfRows ? nil : [self.things objectAtIndex:dropIndex]);
[tableView beginUpdates];
for (id draggedObject in draggedObjects) {
NSInteger from = [newThings indexOfObject:draggedObject];
NSInteger to = (beforeObject ? [newThings indexOfObject:beforeObject] : numberOfRows);
to -= (to > from);
[tableView moveRowAtIndex:from toIndex:to];
[newThings removeObjectAtIndex:from];
if (to == newThings.count) {
[newThings addObject:draggedObject];
} else {
[newThings insertObject:draggedObject atIndex:to];
}
}
self.things = newThings;
[tableView endUpdates];
I then modified it to be index-only based:
NSIndexSet * draggedIndexes = ...;
NSMutableArray * newThings = [[self.things mutableCopy] autorelease];
NSInteger numberOfRows = tableView.numberOfRows;
NSInteger dropIndex = row;
while ([draggedIndexes containsIndex:dropIndex] && dropIndex < numberOfRows) dropIndex++;
[tableView beginUpdates];
NSInteger offsetForIndexesBefore = 0;
NSInteger offsetForIndexesAfter = 0;
NSUInteger initialDraggedIndex = [draggedIndexes firstIndex];
while (initialDraggedIndex != NSNotFound) {
NSInteger from = initialDraggedIndex;
NSInteger to = dropIndex;
id draggedObject = nil;
if (initialDraggedIndex < dropIndex) {
from += offsetForIndexesBefore;
offsetForIndexesBefore--;
}
to -= (to > from);
if (initialDraggedIndex >= dropIndex) {
to += offsetForIndexesAfter;
offsetForIndexesAfter++;
}
draggedObject = [[newThings objectAtIndex:from] retain];
[tableView moveRowAtIndex:from toIndex:to];
[newThings removeObjectAtIndex:from];
if (to == newThings.count) {
[newThings addObject:draggedObject];
} else {
[newThings insertObject:draggedObject atIndex:to];
}
[draggedObject release];
initialDraggedIndex = [draggedIndexes indexGreaterThanIndex:initialDraggedIndex];
}
self.things = newThings;
[tableView endUpdates];
Sample project:
http://www.sethwillits.com/temp/TableViewReorder.zip
--
Seth Willits
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden