Dragging files into other applications in cocoa OSX

╄→尐↘猪︶ㄣ 提交于 2020-01-05 05:37:06

问题


I'm trying to convert a windows application into OSX, everything is working now, except this small feature, the drag&drop of files from my app into any other window that supports drops. Receiving drops it's easy, the problem is being the source of the data to drag.

My application only has 1 window with 1 view, I draw every control myself in there. So I simply extended my view like this @interface NativeView : NSView <NSDraggingSource, NSPasteboardItemDataProvider>.

Now the resto of the code I have so far should work in my opinion, but then again I don't know that much about cocoa and 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];

The fileList is an array of NSString*. And where you see view it means the interface NativeView, it's implemented this way because this is coded within C++;

Currently, the code blocks when I try to set the pasteboard in the pbItem. I mean nothing else is executed past that line. I also tried to get rid of the NSPasteboardall together and use the NSPasteboardItemonly, but I get a EXC_BAD_ACCESS running the last line: beginDraggingSessionWithItems.

I didn't find any examples online about dragging files,all that is is NSImage, and I have no use for that type of drag.

Any help will be welcome, thanks.


回答1:


Yes, the online documentation is pretty lacking.

Try using the following approach:

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]


来源:https://stackoverflow.com/questions/40055527/dragging-files-into-other-applications-in-cocoa-osx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!