Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Opening a file by drag-and-drop in window

Tags:

macos

swift

In Swift, how can I build an area in a window of my Mac app where a user can drag-and-drop a folder onto this area, and have my app receive the path of the folder?

In principle, it seems to me that this is a similar concept to Apple's CocoaDragAndDrop example app. I've tried to work my way through understanding that source code, but the app is written in Objective-C and I've not successfully managed to replicate its functionality in the app I am building.

Thank you in advance.

like image 449
sebthedev Avatar asked Dec 25 '14 05:12

sebthedev


2 Answers

In a custom NSView:

override init(frame frameRect: NSRect)
{
    super.init(frame: frameRect)
    registerForDraggedTypes([kUTTypeFileURL,kUTTypeImage])
}

override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation
{
    println("dragging entered")
    return NSDragOperation.Copy
}

The catch is, to get it working I had to put that custom view as a leaf and the last view in the storyboard

like image 104
user2962499 Avatar answered Sep 21 '22 11:09

user2962499


This worked for me (on a NSWindow subclass):

In awakeFromNib:

registerForDraggedTypes([NSFilenamesPboardType])

Then add the following operations (at least draggingEntered and performDragOperation) to the window (or view):

func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation {
    let sourceDragMask = sender.draggingSourceOperationMask()
    let pboard = sender.draggingPasteboard()!
    if pboard.availableTypeFromArray([NSFilenamesPboardType]) == NSFilenamesPboardType {
        if sourceDragMask.rawValue & NSDragOperation.Generic.rawValue != 0 {
            return NSDragOperation.Generic
        }
    }
    return NSDragOperation.None
}

func draggingUpdated(sender: NSDraggingInfo) -> NSDragOperation {
    return NSDragOperation.Generic
}

func prepareForDragOperation(sender: NSDraggingInfo) -> Bool {
    return true
}

func performDragOperation(sender: NSDraggingInfo) -> Bool {
   // ... perform your magic
   // return true/false depending on success
}
like image 33
Rien Avatar answered Sep 21 '22 11:09

Rien