Drag and Drop in an NSTableView
Friday, July 29th, 2005Drag 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


