Implementations details of drag and drop of file path in cocoa
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 r开发者_StackOverflow社区elation 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?
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.
精彩评论