如何允许用户将文件拖出Cocoa App

时间:2018-01-19 02:01:34

标签: swift macos cocoa drag-and-drop nspasteboard

我正在开发一个涉及在临时目录中创建文件夹的macOS应用程序。

如何让用户将文件夹图标从Cocoa应用程序拖到他们的桌面上(或者放到Finder和其他应用程序中),以便删除它实际上会粘贴应用程序创建的文件夹?

到目前为止,我已经能够将要保存的已完成文件夹写入临时目录。如何在可以拖入Finder的应用程序中放置文件夹图标?谢谢!

我目前正在使用的完整代码是:

    class draggableFolder: NSImageView {
    override func mouseDown(with theEvent: NSEvent) {
        let pasteboardItem = NSPasteboardItem()
       // pasteboardItem.availableType(from: [NSPasteboard.PasteboardType.fileURL])
        pasteboardItem.setDataProvider(self, forTypes: [kUTTypeURL as NSPasteboard.PasteboardType])
        let draggingItem = NSDraggingItem(pasteboardWriter: pasteboardItem)
        draggingItem.setDraggingFrame(self.bounds, contents:self.image)

        beginDraggingSession(with: [draggingItem], event: theEvent, source: self as NSDraggingSource)
    }


}

extension draggableFolder: NSDraggingSource {
    func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {
        return NSDragOperation.generic
    }
}

extension draggableFolder: NSPasteboardItemDataProvider {
    func pasteboard(_ pasteboard: NSPasteboard?, item: NSPasteboardItem, provideDataForType type:
        NSPasteboard.PasteboardType) {
        print("dataprovider")
        if let pasteboard = pasteboard, type.rawValue == String(describing: kUTTypeURL) {
           let folder = currentIconsetURL
            print("dataprovider2")
            print(NSURL.init(fileURLWithPath: currentIconsetURL))
            pasteboard.clearContents()
            pasteboard.declareTypes([NSPasteboard.PasteboardType.fileNameType(forPathExtension: "appiconset")], owner: nil)
            pasteboard.writeObjects([(URL.init(fileURLWithPath: currentIconsetURL).absoluteURL as NSURL) as NSPasteboardWriting])


        }
    }
}

1 个答案:

答案 0 :(得分:2)

可悲的是,Apple的拖放指南完全基于旧的弃用API:https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DragandDrop/DragandDrop.html

使用现代API,您所要求的粗略轮廓是:

  • 您需要一些东西(例如,您的观点)来实现NSDraggingSource协议以返回它仅支持复制操作(draggingSession(_:sourceOperationMaskFor:))。
  • mouseDown(带跟踪循环)或mouseDragged开始,一旦用户的拖动距其原始位置移动了一定距离(全部为3或4个点),那么您应该开始拖动会话(NSView beginDraggingSession
  • 会话应包含一个NSDraggingItem,您可以在其中传入文件夹的网址(作为NSURL,而不是Swift URL,因为只有前者符合NSPasteboardWriter })。