« Dynamically populating an NSPopUpButtonCell in an NSTableView | Main | Cmd - click. The subtle secret of Mac OS X. »

July 28, 2005

Drag and Drop in an NSTableView

Drag and Drop in an NSTableView is easy to do. However, I think the documentation (Table Views: Using Drag and Drop in Tables) for it isn't particularly great. It misses a few points, so I'm going to go over the basic steps on how to add drag and drop to your TableView. Here, I'll assume you have a TableView with your source code controller class set as the delegate.

Declare your custom pasteboard format:

#define BasicTableViewDragAndDropDataType @"BasicTableViewDragAndDropDataType"

In awakeFromNib you must register for the drag types you want to receive (you could have others here):

- (void)awakeFromNib {

    [myTableView registerForDraggedTypes:[NSArray arrayWithObjects:BasicTableViewDragAndDropDataType, nil]];

}

Then, you must implement writeRowsWithIndexes to add your data to the pasteboard:

- (BOOL)tableView:(NSTableView *)tv writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard*)pboard {

    // Drag and drop support

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];

    [pboard declareTypes:[NSArray arrayWithObject:BasicTableViewDragAndDropDataType] owner:self];

    [pboard setData:data forType:BasicTableViewDragAndDropDataType];

    return YES;

}

Next you will validate the drop:

- (NSDragOperation)tableView:(NSTableView*)tv validateDrop:(id <NSDraggingInfo>)info proposedRow:(int)row proposedDropOperation:(NSTableViewDropOperation)op {

    // Add code here to validate the drop

    NSLog(@"validate Drop");

    return NSDragOperationEvery;    

}

Finally, you must have a method that accepts the drop. Here you could access the BasicTableViewDragAndDropDataType and look at the rows that were dragged.

- (BOOL)tableView:(NSTableView*)tv acceptDrop:(id <NSDraggingInfo>)info row:(int)row dropOperation:(NSTableViewDropOperation)op {

    NSLog(@"acceptDrop");

    // Add code here to accept the drop

    return YES;    

}

And that is it! It is pretty easy...

Technorati Tags:

Posted by corbin at July 28, 2005 06:44 PM

Trackback Pings

TrackBack URL for this entry:
http://www.corbinstreehouse.com/cgi-bin/mt-tb.cgi/1

Listed below are links to weblogs that reference Drag and Drop in an NSTableView:

Comments

Corbin,

Thanks for the example code. I'm trying your example of dynamically populating a popup button in a table view. It works great except that the items are disabled. I tried adding a line:
[item setEnabled:TRUE]; to menuNeedsUpdate:. no luck. I've also checked autoenablesItems which defaults to TRUE. Perhaps I need to set that to FALSE?

Thanks.

Posted by: Randy Bradley at September 1, 2005 08:23 AM

Post a comment




Remember Me?