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.
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With