1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
class DropView: NSView { var filePath: String? let expectedExt = ["jpg", "png", "jpeg"] //file extensions allowed for Drag&Drop (example: "jpg","png","docx", etc..) required init?(coder: NSCoder) { super.init(coder: coder) self.wantsLayer = true self.layer?.backgroundColor = NSColor.gray.cgColor registerForDraggedTypes([NSPasteboard.PasteboardType.URL, NSPasteboard.PasteboardType.fileURL]) } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) // Drawing code here. } override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { if checkExtension(sender) == true { self.layer?.backgroundColor = NSColor.blue.cgColor return .copy } else { return NSDragOperation() } } fileprivate func checkExtension(_ drag: NSDraggingInfo) -> Bool { guard let board = drag.draggingPasteboard.propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")) as? NSArray, let path = board[0] as? String else { return false } let suffix = URL(fileURLWithPath: path).pathExtension for ext in self.expectedExt { if ext.lowercased() == suffix { return true } } return false } override func draggingExited(_ sender: NSDraggingInfo?) { self.layer?.backgroundColor = NSColor.gray.cgColor } override func draggingEnded(_ sender: NSDraggingInfo) { self.layer?.backgroundColor = NSColor.gray.cgColor } override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { guard let pasteboard = sender.draggingPasteboard.propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")) as? NSArray, let path = pasteboard[0] as? String else { return false } //GET YOUR FILE PATH !!! self.filePath = path Swift.print("FilePath: \(path)") return true } } |