Swift Drag and Drop在Xcode之外不起作用

时间:2014-09-08 11:41:05

标签: xcode macos debugging drag-and-drop swift

我有一些代码,可以在命令行工具中使用。现在我想把它作为一个Drop-Applet来获取终端和路径。我正在删除一些文件,只要附加调试器就像魅力一样。

到目前为止一直很好,但是当我直接启动它(从Xcode输出目录)时,似乎不接受拖放。 (将文件动画回原点)。

class dragView : NSView, NSDraggingDestination {

 required init(coder: NSCoder) {
     super.init(coder: coder)
 }

 override init(frame: NSRect) {
     super.init(frame: frame)
     let types = [NSFilenamesPboardType, NSURLPboardType]
     registerForDraggedTypes(types)
 }

 override func drawRect(dirtyRect: NSRect)  {
     super.drawRect(dirtyRect)
     NSColor.whiteColor().set()
     NSRectFill(dirtyRect)
 }

 override func draggingEntered(sender: NSDraggingInfo!) -> NSDragOperation  {
     return NSDragOperation.Copy
 }


 override func draggingUpdated(sender: NSDraggingInfo!) -> NSDragOperation {
     return NSDragOperation.Copy
 }

 override func performDragOperation(sender: NSDraggingInfo!) -> Bool {
     let pboard: NSPasteboard = sender.draggingPasteboard()

     let array : [String] = pboard.propertyListForType(String(NSFilenamesPboardType)) as [String]
     for item in array
     {
 ... 

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

您的代码不起作用,因为您必须将拖动类型注册到init(编码器:)功能。 此代码在Swift 3中运行良好

import Cocoa

class DropView : NSView {

    required init?(coder: NSCoder) {
        super.init(coder: coder)

        let types = [NSFilenamesPboardType, NSURLPboardType]
        register(forDraggedTypes: types)

        self.wantsLayer = true
        self.layer?.backgroundColor = NSColor.white.cgColor
    }

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
        // Drawing code here.
    }

    override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation  {
        return .copy
    }

    override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
        guard let pasteboard = sender.draggingPasteboard().propertyList(forType: "NSFilenamesPboardType") as? NSArray,
              let path = pasteboard[0] as? String
        else { return false }

        //GET YOUR FILE PATH !!
        Swift.print("FilePath: \(path)")

        return true
    }
}

更有用的示例here