Swift: open a file by dragging and dropping into a window

In Swift, how can I create an area in the window of my Mac application, where the user can drag a folder into this area, and so that my application gets the path to the folder?

Basically, it seems to me that this is a similar concept for Apple CocoaDragAndDrop example . I tried to find a way to understand the source code, but the application is written in Objective-C, and I was unable to replicate its functions in the application that I am creating.

Thanks in advance.

+5
source share
2 answers

In 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 trick to make it work, I had to put this custom view as a sheet and the last view in the storyboard

+4
source

This worked for me (in a subclass of NSWindow):

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 } 
+2
source

Source: https://habr.com/ru/post/1209866/


All Articles