1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swift:NSColorをドラッグ&ドロップでコピペする

Posted at

demo

demo.gif

ソース

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
    }
}
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?