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
  // 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
  NSLog(@“acceptDropâ€);
  // Add code here to accept the drop
  return YES;  Â
}
And that is it! It is pretty easy…
Technorati Tags: Cocoa
Thanks! I found it difficult to determine exactly which delegate methods needed to be called when, while first deciphering the “DragNDrop TableView” example. This post makes a concise summary for future reference.
Daniel — I agree! I think we need more demos of exactly what to do for what particular case. Hopefully this will help a few people.
Hi Corbin,
Thanks! I have been looking around the web for something like this. It all looks great and looks similar to the “bookmarks” example I found, but my “tableView: validateDrop:…” never gets called, although it’s in the same file as “tableView:writeRowsWithIndexes:…” which gets called fine.
Any suggestions?
Thanks.
[…] of the Documentation for it is fairly complicated. However, I stumbled across this lovely blog post by Corbin, which had these few easy steps (slightly edited here)… Declare your custom […]
note that this stuff is now in the latest ADC update. Yes! Thanks apple doc team!
The thing I could not achieved is to drag from a table view to the Finder (like it could create a clipping wih text in the row).