BoundNSTableViewDragAndDropDataSource.m from redshed at Krugle
Show BoundNSTableViewDragAndDropDataSource.m syntax highlighted
#import "BoundNSTableViewDragAndDropDataSource.h"
#import "nsenumerate.h"
NSString *DraggedRowIndexesType = @"DraggedRowIndexesType";
static void rearrangeTableArray(NSArrayController *tableArray, NSArray *sourceRowIndexes, int destinationRowIndex) {
// Ensure the numbers are in order.
sourceRowIndexes = [sourceRowIndexes sortedArrayUsingSelector:@selector(compare:)]; // Ensure they're in order.
// In reverse order, add each source row to a temporary container and then remove it from the tableArray.
// Since we've altered the tableArray by removing a row, decrement the destinationRowIndex if it pointed
// at a row that got shifted with the row removal.
NSMutableArray *tempContainer = [NSMutableArray arrayWithCapacity:[sourceRowIndexes count]];
nsenumerate([sourceRowIndexes reverseObjectEnumerator], NSNumber, sourceRowIndexObj) {
int sourceRowIndex = [sourceRowIndexObj intValue];
[tempContainer addObject:[[tableArray arrangedObjects] objectAtIndex:sourceRowIndex]];
[tableArray removeObjectAtArrangedObjectIndex:sourceRowIndex];
if (sourceRowIndex < destinationRowIndex && destinationRowIndex != 0) {
destinationRowIndex--;
}
}
// Now all the source rows have been removed from the table. Put them back at the requested destination row index.
nsenumerat(tempContainer, movedObject) {
[tableArray insertObject:movedObject atArrangedObjectIndex:destinationRowIndex];
}
}
@implementation BoundNSTableViewDragAndDropDataSource
- (void)awakeFromNib {
[tableView registerForDraggedTypes:[NSArray arrayWithObject:DraggedRowIndexesType]];
}
- (BOOL)tableView:(NSTableView*)tableView_
writeRows:(NSArray*)rows_
toPasteboard:(NSPasteboard*)pb
{
[pb declareTypes:[NSArray arrayWithObject:DraggedRowIndexesType] owner:self];
[pb setPropertyList:rows_ forType:DraggedRowIndexesType];
return YES;
}
- (NSDragOperation)tableView:(NSTableView*)tableView_
validateDrop:(id<NSDraggingInfo>)info_
proposedRow:(int)row_
proposedDropOperation:(NSTableViewDropOperation)operation_
{
NSDragOperation result = NSDragOperationNone;
if (tableView_ == tableView
&& NSTableViewDropAbove == operation_
&& [info_ draggingSource] == tableView
&& [[info_ draggingPasteboard] availableTypeFromArray:[NSArray arrayWithObject:DraggedRowIndexesType]])
{
result = NSDragOperationMove;
}
return result;
}
- (BOOL)tableView:(NSTableView*)tableView_
acceptDrop:(id<NSDraggingInfo>)info_
row:(int)row_
dropOperation:(NSTableViewDropOperation)operation_
{
NSDragOperation result = NO;
NSPasteboard *pb = [info_ draggingPasteboard];
if (tableView_ == tableView
&& NSTableViewDropAbove == operation_
&& [info_ draggingSource] == tableView
&& [pb availableTypeFromArray:[NSArray arrayWithObject:DraggedRowIndexesType]])
{
rearrangeTableArray(arrayController, [pb propertyListForType:DraggedRowIndexesType], row_);
result = YES;
}
return result;
}
@end
See more files for this project here