How to support drag and drop in NSView

Khoa Pham
Khoa Pham
Nov 6, 2019 · 1 min read
import AppKit
import Anchors

class DraggingView: NSView {
var didDrag: ((FileInfo) -> Void)?
let highlightView = NSView()

override init(frame frameRect: NSRect) {
super.init(frame: frameRect)

registerForDraggedTypes([
.fileURL
])

highlightView.isHidden = true
addSubview(highlightView)
activate(highlightView.anchor.edges)
highlightView.wantsLayer = true
highlightView.layer?.borderColor = NSColor(hex: "#FF6CA8").cgColor
highlightView.layer?.borderWidth = 6
}

required init?(coder decoder: NSCoder) {
fatalError()
}

override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
highlightView.isHidden = false
return NSDragOperation()
}

override func draggingEnded(_ sender: NSDraggingInfo) {
guard let pathAlias = sender.draggingPasteboard.propertyList(forType: .fileURL) as? String else {
return
}

let url = URL(fileURLWithPath: pathAlias).standardized
let fileInfo = FileInfo(url: url)
didDrag?(fileInfo)
}

override func draggingExited(_ sender: NSDraggingInfo?) {
highlightView.isHidden = true
}

override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
return NSDragOperation()
}
}

To get information about multiple files

override func draggingEnded(_ sender: NSDraggingInfo) {
guard let pasteBoardItems = sender.draggingPasteboard.pasteboardItems else {
return
}

let fileInfos: [FileInfo] = pasteBoardItems
.compactMap({
return $0.propertyList(forType: .fileURL) as? String
})
.map({
let url = URL(fileURLWithPath: $0).standardized
return FileInfo(url: url)
})

didDrag(fileInfos)
}

Fantageek

Simple apps that make sense

Khoa Pham

Written by

Khoa Pham

My apps https://onmyway133.github.io/

Fantageek

Fantageek

Simple apps that make sense

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade