| import Cocoa |
| |
| @available(macOS 10.13, *) |
| let imagePboardType = NSPasteboard.PasteboardType.fileURL |
| |
| class DragSourceView: NSImageView { |
| weak var dragSourceDelegate: NSDraggingSource? |
| override func mouseDown(with event: NSEvent) { |
| |
| |
| let pasteboardItem = NSPasteboardItem() |
| |
| if #available(macOS 10.13, *) { |
| pasteboardItem.setDataProvider(self, forTypes: [NSPasteboard.PasteboardType.fileURL]) |
| } else { |
| |
| } |
| |
| |
| let draggingItem = NSDraggingItem(pasteboardWriter: pasteboardItem) |
| draggingItem.draggingFrame = NSRect(x: 100 , y: 10, width: 100, height: 100) |
| |
| |
| draggingItem.imageComponentsProvider = { |
| |
| let component = NSDraggingImageComponent(key: NSDraggingItem.ImageComponentKey.icon) |
| |
| component.frame = NSRect(x: 0, y: 0, width: 16, height: 16) |
| component.contents = NSImage(size: NSSize(width: 32,height: 32), flipped: false, drawingHandler: { [unowned self] rect in { |
| |
| self.image?.draw(in: rect) |
| |
| return true |
| }() |
| } |
| ) |
| return [component] |
| } |
| |
| self.beginDraggingSession(with: [draggingItem], event: event, source: self.dragSourceDelegate!) |
| } |
| } |
| |
| |
| extension DragSourceView: NSPasteboardItemDataProvider { |
| func pasteboard(_ pasteboard: NSPasteboard?, item: NSPasteboardItem, provideDataForType type: NSPasteboard.PasteboardType) { |
| |
| |
| let data = "/Users/slowdony/Desktop/640.jpeg" |
| let dataUrl = data.data(using: String.Encoding(rawValue: NSUTF8StringEncoding))! |
| item.setData(dataUrl, forType: type) |
| } |
| } |
| |
| import Cocoa |
| |
| |
| class ViewController: NSViewController { |
| @IBOutlet weak var sourceView: DragSourceView! |
| override func viewDidLoad() { |
| super.viewDidLoad() |
| self.sourceView.dragSourceDelegate = self |
| } |
| } |
| |
| extension ViewController: NSDraggingSource { |
| |
| |
| func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation { |
| if (context == .outsideApplication){ |
| return .copy |
| } |
| else{ |
| return .generic |
| } |
| } |
| |
| |
| func draggingSession(_ session: NSDraggingSession, willBeginAt screenPoint: NSPoint) { |
| print("draggingSession beginAt \(screenPoint)") |
| } |
| |
| |
| func draggingSession(_ session: NSDraggingSession, movedTo screenPoint: NSPoint) { |
| print("draggingSession movedTo \(screenPoint)") |
| } |
| |
| |
| func draggingSession(_ session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) { |
| print("draggingSession endedAt \(screenPoint)") |
| } |
| } |
I am dragging an image to the desktop through the above code, failed, help