Cocoa中的拖放(<NSDraggingDestination>)不起作用

the*_*tic 2 xcode cocoa drag-and-drop nsdragginginfo

我想在我的Mac应用程序中实现一些"简单"的拖放操作.我在视图中拖动并相应地在我的nib文件中输入"MyView".但是我的控制台中没有得到任何响应(我尝试在触发任何协议方法时记录消息)

我有这样的NSView子类:

@interface MyView : NSView <NSDraggingDestination>{
    NSImageView* imageView;
}
Run Code Online (Sandbox Code Playgroud)

并像这样实现它:

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        [self registerForDraggedTypes:[NSImage imagePasteboardTypes]];

        NSRect rect = NSMakeRect(150, 0, 400, 300);
        imageView = [[NSImageView alloc] initWithFrame:rect];

        [imageView setImageScaling:NSScaleNone];
        [imageView setImage:[NSImage imageNamed:@"test.png"]];
        [self addSubview:imageView];



    }

    return self;
}


- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender{
    NSLog(@"entered");
    return NSDragOperationCopy;

}

- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender{
    return NSDragOperationCopy;

}


- (void)draggingExited:(id <NSDraggingInfo>)sender{
    NSLog(@"exited");

}
- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender{
    NSLog(@"som");
    return YES;

}

- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {

    NSPasteboard *pboard = [sender draggingPasteboard];

    if ( [[pboard types] containsObject:NSURLPboardType] ) {
        NSURL *fileURL = [NSURL URLFromPasteboard:pboard];
        NSLog(@"%@", fileURL);
    }
    return YES;
}

- (void)concludeDragOperation:(id <NSDraggingInfo>)sender{
    NSLog(@"conclude sth");


}

- (void)draggingEnded:(id <NSDraggingInfo>)sender{
    NSLog(@"ended");


}

- (BOOL)wantsPeriodicDraggingUpdates{
    NSLog(@"wants updates");

}


- (void)updateDraggingItemsForDrag:(id <NSDraggingInfo>)sender NS_AVAILABLE_MAC(10_7){
}
Run Code Online (Sandbox Code Playgroud)

Mel*_*ign 11

如果有人仍然需要这个,使用:

[self registerForDraggedTypes:[NSArray arrayWithObjects: 
                       NSFilenamesPboardType, nil]];
Run Code Online (Sandbox Code Playgroud)

代替:

[self registerForDraggedTypes: 
                      [NSImage imagePasteboardTypes]]; // BAD: dropped image runs away, no draggingdestination protocol methods sent...
Run Code Online (Sandbox Code Playgroud)

为我解决了这个问题.我怀疑这是有效的,因为我的XIB针对的是osX 10.5.NSFilenamesPboardType表示10.5和之前的"标准数据"UTI,[NSImage imagePasteboardTypes]返回标准数据UTI之后的10.6和之后.

顺便说一下,在- (BOOL)performDragOperation:(id NSDraggingInfo)发送方中,您可以获取丢弃的文件的路径:

 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
Run Code Online (Sandbox Code Playgroud)

得到了解决方案:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DragandDrop/Tasks/acceptingdrags.html#//apple_ref/doc/uid/20000993-BABHHIHC