Last active
January 31, 2020 20:10
-
-
Save fpg1503/8efc383e416b0d4aecac7717a8ad976e to your computer and use it in GitHub Desktop.
Drag and Drop View on macOS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol DragViewDelegate { | |
var acceptedFileExtensions: [String] { get } | |
func dragView(dragView: DragView, didDragFileWith URL: NSURL) | |
} | |
class DragView: NSView { | |
required init?(coder: NSCoder) { | |
super.init(coder: coder) | |
registerForDraggedTypes([NSFilenamesPboardType, NSURLPboardType]) | |
} | |
private var fileTypeIsOk = false | |
private var acceptedFileExtensions: [String] { | |
return delegate?.acceptedFileExtensions ?? [] | |
} | |
var delegate: DragViewDelegate? | |
override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation { | |
if checkExtension(sender) { | |
fileTypeIsOk = true | |
return .Copy | |
} else { | |
fileTypeIsOk = false | |
return .None | |
} | |
} | |
override func draggingUpdated(sender: NSDraggingInfo) -> NSDragOperation { | |
if fileTypeIsOk { | |
return .Copy | |
} else { | |
return .None | |
} | |
} | |
override func performDragOperation(sender: NSDraggingInfo) -> Bool { | |
guard let draggedFileURL = sender.draggedFileURL else { | |
return false | |
} | |
delegate?.dragView(self, didDragFileWith: draggedFileURL) | |
return true | |
} | |
func checkExtension(drag: NSDraggingInfo) -> Bool { | |
guard let fileExtension = drag.draggedFileURL?.pathExtension?.lowercaseString else { | |
return false | |
} | |
return acceptedFileExtensions.contains(fileExtension) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension NSDraggingInfo { | |
var draggedFileURL: NSURL? { | |
let filenames = draggingPasteboard().propertyListForType(NSFilenamesPboardType) as? [String] | |
let path = filenames?.first | |
return path.map(NSURL.init) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment