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()
//设置数据的Provider
if #available(macOS 10.13, *) {
pasteboardItem.setDataProvider(self, forTypes: [NSPasteboard.PasteboardType.fileURL])
} else {
// Fallback on earlier versions
}
//拖放item
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]
}
//开始启动拖放sesson
self.beginDraggingSession(with: [draggingItem], event: event, source: self.dragSourceDelegate!)
}
}
extension DragSourceView: NSPasteboardItemDataProvider {
func pasteboard(_ pasteboard: NSPasteboard?, item: NSPasteboardItem, provideDataForType type: NSPasteboard.PasteboardType) {
// let data = self.image?.tiffRepresentation
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