【问题标题】:Dragging files into other applications in cocoa OSX将文件拖入 cocoa OSX 中的其他应用程序
【发布时间】:2017-02-24 14:46:36
【问题描述】:

我正在尝试将 Windows 应用程序转换为 OSX,现在一切正常,除了这个小功能,将文件从我的应用程序拖放到任何其他支持拖放的窗口。接收drop很容易,问题是要拖动的数据源。

我的应用程序只有 1 个窗口和 1 个视图,我自己在其中绘制每个控件。所以我只是像这样扩展了我的观点@interface NativeView : NSView <NSDraggingSource, NSPasteboardItemDataProvider>

现在我认为到目前为止我所拥有的代码的恢复应该可以工作,但是我对 cocoa 和 OSX 的了解并不多:

NSArray *fileList = [NSArray arrayWithObjects:&pathList[0] count:pathList.size()];

NSPasteboard *pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
[pboard declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType] owner:nil];
[pboard setPropertyList:fileList forType:NSFilenamesPboardType];

NSPasteboardItem *pbItem = [NSPasteboardItem new];
[pbItem setDataProvider:view forTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];
[pbItem pasteboard:pboard provideDataForType:NSFilenamesPboardType];

NSDraggingItem *dragItem = [[NSDraggingItem alloc] initWithPasteboardWriter:pbItem];
[dragItem setDraggingFrame:NSMakeRect(0, 0, 10, 10)];


[view beginDraggingSessionWithItems:[NSArray arrayWithObjects:dragItem, nil] event:mouseEvent source:view];

fileList 是一个NSString* 的数组。在你看到view 的地方,它表示接口NativeView,它是这样实现的,因为它是在C++ 中编码的;

目前,当我尝试在pbItem 中设置pasteboard 时,代码会阻塞。我的意思是在这条线之后没有执行任何其他操作。我还尝试将NSPasteboardall 一起删除并仅使用NSPasteboardItem,但我得到一个运行最后一行的EXC_BAD_ACCESS:beginDraggingSessionWithItems

我在网上没有找到任何关于拖动文件的例子,都是NSImage,我没有用这种类型的拖动。

欢迎任何帮助,谢谢。

【问题讨论】:

    标签: objective-c macos cocoa drag-and-drop nspasteboard


    【解决方案1】:

    是的,在线文档非常缺乏。

    尝试使用以下方法:

    auto* dragItems = [[NSMutableArray alloc] init];
    for (auto& path : pathList)
    {
        auto* fileURL = [NSURL fileURLWithPath: path];
        auto* dragItem = [[NSDraggingItem alloc] initWithPasteboardWriter: fileURL];
        [dragItem setDraggingFrame: NSMakeRect(0, 0, 10, 10)];
        [dragItems addObject: dragItem];
    }
    
    [view beginDraggingSessionWithItems: dragItems
                                  event: mouseEvent
                                 source: view]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多