【问题标题】:Drag & drop (<NSDraggingDestination>) in Cocoa does not workCocoa 中的拖放 (<NSDraggingDestination>) 不起作用
【发布时间】:2012-08-28 21:54:28
【问题描述】:

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

我已经像这样子类化了 NSView:

@interface MyView : NSView <NSDraggingDestination>{
    NSImageView* imageView;
}

并像这样实现它:

- (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){
}

【问题讨论】:

    标签: xcode cocoa drag-and-drop nsdragginginfo


    【解决方案1】:

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

    [self registerForDraggedTypes:[NSArray arrayWithObjects: 
                           NSFilenamesPboardType, nil]];
    

    代替:

    [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 中,您可以获取被删除的文件的路径:

     NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
    

    在这里找到解决方案:

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

    【讨论】:

    • imagePasteboardTypes = 仅图像内容
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    • 2015-08-10
    • 2018-06-16
    相关资源
    最近更新 更多