首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何允许用户将文件拖出Cocoa应用程序

如何允许用户将文件拖出Cocoa应用程序
EN

Stack Overflow用户
提问于 2018-01-19 02:01:34
回答 1查看 1.6K关注 0票数 6

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

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

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

我目前使用的完整代码如下:

代码语言:javascript
复制
    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])


        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-01-19 17:30:51

遗憾的是,苹果公司的拖放指南完全基于旧的被废弃的API:https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DragandDrop/DragandDrop.html

使用现代API,您所要求的内容的大致大纲是:

  • 您需要一些东西(例如,您的视图)来实现NSDraggingSource协议,以返回它只支持复制操作(draggingSession(_:sourceOperationMaskFor:))。
  • mouseDown (带有跟踪环)或mouseDragged中,一旦用户的拖动从原来的位置移动了一定的距离(全部是3或4个点),那么您应该启动一个拖放会话(NSView beginDraggingSession)。
  • 会话应该包含一个NSDraggingItem,您在其中传递文件夹的URL (作为NSURL,而不是Swift URL,因为只有前者符合NSPasteboardWriter)。
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48333103

复制
相关文章

相似问题

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