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

后端 未结 3 2068
傲寒
傲寒 2021-02-06 10:49

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 pr

3条回答
  •  再見小時候
    2021-02-06 11:29

    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
    }
    

提交回复
热议问题