Swift Drag and Drop won't work outside of Xcode

I have some code that works in a command line tool. Now I wanted to do this with a Drop app to get to the terminal and paths. I dump some files into it and as long as the debugger is connected it works like a charm.

So far so good, but when I run it directly (from Xcode's output directory) it seems like drag / drop is not accepted. (File animation back to the beginning).

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
     {
 ... 

      

What am I missing here?

+3


source to share


1 answer


Your code doesn't work because you have to register the dragged type in the init (coder :) function. This code works fine in 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
    }
}

      



More useful example here

0


source







All Articles