首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Cocoa中的拖放(<NSDraggingDestination>)不起作用

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

Stack Overflow用户
提问于 2012-08-29 05:54:29
回答 1查看 3.4K关注 0票数 3

我想实现一些“简单的”拖放到我的Mac应用程序中。我拖入一个视图,并在nib文件中输入"MyView“accordingly.However我在控制台中没有得到任何响应(每当触发任何协议方法时,我都会尝试记录消息)

我将NSView子类化如下:

代码语言:javascript
复制
@interface MyView : NSView <NSDraggingDestination>{
    NSImageView* imageView;
}

并像这样实现它:

代码语言:javascript
复制
- (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){
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-11 02:29:48

如果任何人仍然需要它,请使用:

代码语言:javascript
复制
[self registerForDraggedTypes:[NSArray arrayWithObjects: 
                       NSFilenamesPboardType, nil]];

而不是:

代码语言:javascript
复制
[self registerForDraggedTypes: 
                      [NSImage imagePasteboardTypes]]; // BAD: dropped image runs away, no draggingdestination protocol methods sent...

为我解决了这个问题。我怀疑这是可行的,因为我的XIB针对的是osX 10.5。NSFilenamesPboardType表示10.5及更早版本的“标准数据”UTI,而NSImage imagePasteboardTypes返回10.6及更高版本的标准数据UTI。

顺便说一下,在- (BOOL)performDragOperation:(id NSDraggingInfo)sender中,您可以使用以下命令获取被丢弃的文件的路径:

代码语言:javascript
复制
 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];

在这里得到了解决方案:

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

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12168059

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档