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
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
{
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:
change NSLog(@"%@",[self.files objectAtIndex:i]); to
NSLog(@"%@",[files objectAtIndex:i]); because the compiler is fussy about dot syntax sometimes.
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).
@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.
Useful indeed. Cheers.
Post a Comment