views:

77

answers:

1

Hi,

I'm trying to get a part of my window to react to drag and drop. In this case to copy the file path to the file being dropped on the view. I have looked over some documentation but I still have some problems to see exactly where I should implement my methods for drag and drop.

I have seen some examples but almost all of them assumes that I want to drop an image on the view. I'm pretty new to cocoa and Xcode so, I have some problems with seeing the exact relation between interface builder and the generated code.

I have created a subclass to NSView, called drop zone like this:

#import <Cocoa/Cocoa.h>

@interface dropZone : NSView {

}

@end

I then use an NSRect to color it grey like this:

#import "dropZone.h"

@implementation dropZone


- (void)drawRect:(NSRect)rect
{

    NSRect bounds = [self bounds];
    [[NSColor grayColor] set];
    [NSBezierPath fillRect:bounds];
}
@end

I then drag this class to my window in interface builder. But I will need to implement the registerForDraggingTypes method, but where? I have also seen a convenience method in the Apple docs for file paths like this: dragFile:fromRect:slideBack:event: that might work.

Should I use the first responder? A init method or what?

+2  A: 

You don't have to override registerForDraggedTypes:. You just have to invoke it. However, you will have to override the methods to respond to entering your view with a drag, or releasing a drag, etc. So if you have a view that needs to accept drops of type MyCustomDropType, then you do:

[myView registerForDraggedTypes:[NSArray arrayWithObject:MyCustomDropType]];

Then your dragging methods will only fire if the drag has been declared to offer MyCustomDropType data.

Dave DeLong
Thank you. If I do this: `[self registeredDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];` in my drawRect method I get the following error: `dropZone may not respond to -registeredDraggedTypes`.
foo
Don't use `[self registeredDraggedTypes:...];`, use `[self registerForDraggedTypes:...]`
Dave DeLong
Aah, a mistake on my part :-). It compiles now and the view appears to be taking the file. Thank you!
foo