Created
February 25, 2018 03:12
-
-
Save KrisYu/e531381e407044cf59c48138997d7746 to your computer and use it in GitHub Desktop.
Drag and Drop for macos
This file contains 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
import Cocoa | |
protocol DragContainerDelegate { | |
func draggingEntered() | |
func draggingExit() | |
func draggingFileAccept(_ files: [URL]) | |
} | |
// https://stackoverflow.com/questions/29233247/implementing-a-drag-and-drop-zone-in-swift | |
class DragContainer: NSView { | |
var delegate: DragContainerDelegate? | |
let acceptTypes = ["png", "jpg", "jpeg"] | |
override init(frame frameRect: NSRect) { | |
super.init(frame: frameRect) | |
setup() | |
} | |
required init?(coder decoder: NSCoder) { | |
super.init(coder: decoder) | |
setup() | |
} | |
// https://stackoverflow.com/questions/29233247/implementing-a-drag-and-drop-zone-in-swift | |
func setup(){ | |
registerForDraggedTypes([NSPasteboard.PasteboardType(kUTTypeTIFF as String), | |
NSPasteboard.PasteboardType(kUTTypeURL as String)]) | |
} | |
override func draw(_ dirtyRect: NSRect) { | |
super.draw(dirtyRect) | |
} | |
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { | |
delegate?.draggingEntered() | |
let acceptFiles = checkExtension(sender) | |
return acceptFiles ? NSDragOperation.generic : NSDragOperation() | |
} | |
override func draggingExited(_ sender: NSDraggingInfo?) { | |
delegate?.draggingExit() | |
} | |
override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool { | |
return true | |
} | |
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { | |
var files: [URL] = [] | |
if let board = sender.draggingPasteboard().propertyList(forType: NSPasteboard.PasteboardType(rawValue:"NSFilenamesPboardType")) as? [String] { | |
for path in board { | |
let url = URL(fileURLWithPath: path) | |
let fileExtension = url.pathExtension.lowercased() | |
if acceptTypes.contains(fileExtension){ | |
files.append(url) | |
} | |
} | |
} | |
delegate?.draggingFileAccept(files) | |
return true | |
} | |
// https://stackoverflow.com/questions/31657523/os-x-swift-get-file-path-using-drag-and-drop | |
func checkExtension(_ draggingInfo: NSDraggingInfo) -> Bool { | |
if let board = draggingInfo.draggingPasteboard().propertyList(forType: NSPasteboard.PasteboardType(rawValue:"NSFilenamesPboardType")) as? [String] { | |
for path in board { | |
let url = URL(fileURLWithPath: path) | |
let fileExtension = url.pathExtension.lowercased() | |
if acceptTypes.contains(fileExtension) { | |
return true | |
} | |
} | |
} | |
return false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment