Drag & Drop in NSView

Add drag & drop action in NSView.

Steps

  1. Create delegate to handle operation outside of NSView
  2. Implement draggingEntered in NSView
  3. Implement performDragOperation in NSView
  4. Use registerForDraggedTypes in initWithFrame

Sample

Delegate

@protocol DropDelegate <NSObject>
-(void)parseData:(NSURL *)fileURL;
@end

Header

@interface DropView : NSView
@property (nonatomic) id<DropDelegate>dropdelegate;
-(NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender;
-(BOOL)performDragOperation:(id<NSDraggingInfo>)sender;
@end

Code

@implementation DropView

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
    [[NSColor colorWithDeviceWhite:1.0 alpha:0.75] set];
    NSRectFillUsingOperation(dirtyRect, NSCompositeSourceOver);
}

#pragma mark - Drag & Drop
-(NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender
{
    NSPasteboard *pboard;
    NSDragOperation sourceDragMask;
    sourceDragMask = [sender draggingSourceOperationMask];
    pboard = [sender draggingPasteboard];
    
    if ( [[pboard types] containsObject:NSFilenamesPboardType] )
    {
        if (sourceDragMask & NSDragOperationCopy)
        {
            return NSDragOperationCopy;
        }
    }
    return NSDragOperationNone;
}

-(BOOL)performDragOperation:(id<NSDraggingInfo>)sender
{
    
    NSPasteboard *pboard = [sender draggingPasteboard];
    
    if ( [[pboard types] containsObject:NSURLPboardType] )
    {
        NSURL *fileURL = [NSURL URLFromPasteboard:pboard];
        [self.dropdelegate parseData:fileURL];
    }
    return YES;
}
@end

How to use?

Implement DropDelegate in UI handler.
Set delegate.