import Cocoa
extension NSColor {
var swatch: NSImage {
let size = NSSize(width: 25.0, height: 25.0)
let image = NSImage(size: size)
image.lockFocus()
self.drawSwatch(in: NSRect(origin: .zero, size: size))
image.unlockFocus()
return image
}
}
class ColorView: NSView {
var color: NSColor = .white
required init?(coder: NSCoder) {
super.init(coder: coder)
registerForDraggedTypes([.color])
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
color.setFill()
NSBezierPath(rect: dirtyRect).fill()
}
override func mouseDragged(with event: NSEvent) {
let draggingItem = NSDraggingItem(pasteboardWriter: color)
let swatch = color.swatch
draggingItem.setDraggingFrame(CGRect(origin: .zero, size: swatch.size), contents: swatch)
beginDraggingSession(with: [draggingItem], event: event, source: self)
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
if let _ = NSColor(from: sender.draggingPasteboard) {
return .copy
}
return []
}
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
if let _ = NSColor(from: sender.draggingPasteboard) {
return .copy
}
return []
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
guard let newColor = NSColor(from: sender.draggingPasteboard) else {
return false
}
color = newColor
self.needsDisplay = true
return true
}
}
extension ColorView: NSDraggingSource {
func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {
return .copy
}
}