How to support Drag & Drop for OutlineView

I have taken 1 days to add the drag & drop feature for NSOutlineView,actually,before it took me 3 days to understand how NSOutlineView work.

Okay, let's start!

First,you should register the data type you want to drag and drop and make the NSOutlineView support drag and drop.

Please do it like this:

[outlineView registerForDraggedTypes:[NSArray arrayWithObjects: @"CustomType.2",nil]];
[outlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
The type should be a array,and in general,we use custom type,so you should use a string to define it.and there is a point need to notice,it is that at best you should make the string's format is @"abc.abc",if you don't do it like this,maybe you will be failed!

Then you need to override some methods to response the user's drag and drop operations in the NSOutlineView,They are:

- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pasteboard
{
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:items];
    [pasteboard declareTypes:[NSArray arrayWithObject: @"CustomType.2"] owner:self];
    [pasteboard setData:data forType: @"CustomType.2"];
    return YES;
}

- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop:(id<NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
{
    NSLog(@"Drop 1");
    return NSDragOperationEvery;
}

- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop:(id<NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
{
    NSLog(@"Drop 2");
    //do something...
    //if return NO,the drag & drop operation will not be completed.
    return YES;
}

The other point need to notice is that if table view also need to support,the first method maybe some difference,you should reference the documentation.

and the data type used in the first method should be same to the type registered.

If anyone need the demo,please leave your email,and I will send to you~

你可能感兴趣的:(How to support Drag & Drop for OutlineView)