Drag and drop from within a NSOutlineView

本秂侑毒 提交于 2019-12-05 04:06:02

I have found the documentation of this to be somewhat unclear, and among other things the new ways to do it were added in Lion.

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

In your data source/delegate class, implement:

// 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 good deal of code needed to be filled in for the last method, and regarding the animated movement, Apple's complex table view demo code mentioned in samir's comment is quite useful, if somewhat complex to decipher.

I have created a small sample project which has an NSOutlineView where you can add and remove items.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!