Wednesday, January 26, 2011

Multiple Drop - Objective C Sample Code

The sample code below shows how you could customise a NSView to accept drag and drop of files. The code will give you the file path(s) of the dropped file(s).

Steps
1. Create a subclass of NSView by using the code blow
2. Add a NSView using interface builder to your app window
3. Change the NSView's class to your new subclass (in this case, to DropArea)
4. Run the app
5. Drag file(s) to the view and drop when the cursor changes
6. The app will print the file path(s) of the dropped file(s). Open the console to see :)


@interface DropArea : NSView {
}

@end


#import "DropArea.h"

@implementation DropArea

- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
[self registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];

}
return self;
}

- (void)drawRect:(NSRect)dirtyRect {
// Drawing code here.
}

- (NSDragOperation)draggingEntered:(id )sender {
NSPasteboard *pboard;
NSDragOperation sourceDragMask;

sourceDragMask = [sender draggingSourceOperationMask];
pboard = [sender draggingPasteboard];

if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
if (sourceDragMask & NSDragOperationLink) {
return NSDragOperationLink;
} else if (sourceDragMask & NSDragOperationCopy) {
return NSDragOperationCopy;
}
}
return NSDragOperationNone;
}

- (BOOL)performDragOperation:(id )sender
{
NSPasteboard *pboard = [sender draggingPasteboard];

if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
// Perform operation using the list of files
NSLog(@"Dragged files");
int i;
for (i = 0; i < [files count]; i++) {

NSLog(@"%@",[self.files objectAtIndex:i]);
}
}
return YES;
}

- (void)dealloc{

[super dealloc];
}

@end

4 comments:

Eric said...

change NSLog(@"%@",[self.files objectAtIndex:i]); to
NSLog(@"%@",[files objectAtIndex:i]); because the compiler is fussy about dot syntax sometimes.

Chas said...

Noob question: How do I get the result (array of dropped files) back to my controller class so I can do something useful with it (like add it to an ArrayController).

ThE uSeFuL said...

@Chas,
Have an instance of your controller class inside the subclass of NSView (in this case inside the "DropArea") and pass the array as a parameter to a method in it.

Chas said...

Useful indeed. Cheers.