Drag & Drop in NSView
Add drag & drop action in NSView.
Steps
- Create delegate to handle operation outside of NSView
- Implement draggingEntered in NSView
- Implement performDragOperation in NSView
- 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.
How do I do this in swift? I want to create a icon on the desktop and be able to drag documents or photos or webpages into it. Any help would be appreciated