Drag and Drop from NSOutlineView

I am trying to figure out how to implement drag and drop from within NSOutlineView for myself.

For example, I want the user to be able to reorder and nest and reinstall elements in NSOutlineView, but I do not need to drag and drop elements from any other source (for example, files or from another view).

All the examples that I can find relate to dragging and dropping an element into NSOutlineView, not just within myself, and seem overly complex. I guess this is possible.

Can someone point out some documents that concern this particular case? Maybe I'm just missing the obvious.

+7
source share
2 answers

I found the documentation about this somewhat obscure, and among other things, Lion added new ways to do this.

Assuming you need this for 10.7 or higher, this could be the skeleton for the implementation:

In your data source / delegate class, do:

// A method to register the view for dragged items from itself. // Call it during initialization -(void) enableDragNDrop { [self.outlineView registerForDraggedTypes: [NSArray arrayWithObject: @"DragID"]]; } - (id <NSPasteboardWriting>)outlineView:(NSOutlineView *)outlineView pasteboardWriterForItem:(id)item { // No dragging if <some condition isn't met> if ( dontDrag ) { return nil; } // With all the blocking conditions out of the way, // return a pasteboard writer. // Implement a uniqueStringRepresentation method (or similar) // in the classes that you use for your items. // If you have other ways to get a unique string representation // of your item, you can just use that. NSString *stringRep = [item uniqueStringRepresentation]; NSPasteboardItem *pboardItem = [[NSPasteboardItem alloc] init]; [pboardItem setString:stringRep forType: @"DragID"]; return pboardItem; } - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id < NSDraggingInfo >)info proposedItem:(id)item proposedChildIndex:(NSInteger)index { BOOL dragOK = // Figure out if your dragged item(s) can be dropped // on the proposed item at the index given if ( dragOK ) { return NSDragOperationMove; } else { return NSDragOperationNone; } } - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id < NSDraggingInfo >)info item:(id)item childIndex:(NSInteger)index { // Move the dragged item(s) to their new position in the data model // and reload the view or move the rows in the view. // This is of course quite dependent on your implementation } 

There is a lot of code that needs to be filled out for the latter method and with respect to the animated movement, Apple's integrated table view demo code mentioned in the comment by Samir is very useful if it is somewhat difficult to decrypt.

+12
source

I created a small project in which there is NSOutlineView , where you can add and remove elements.

Today I implemented support for Drag and Drop based on @Monolo's answer ( See changes ).

screenshot

+7
source

All Articles