Implementing a drag-and-drop zone in Swift
Swift 4
class MyImageView: NSImageView {
let NSFilenamesPboardType = NSPasteboard.PasteboardType("NSFilenamesPboardType")
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
// Declare and register an array of accepted types
registerForDraggedTypes([NSPasteboard.PasteboardType(kUTTypeFileURL as String),
NSPasteboard.PasteboardType(kUTTypeItem as String)])
}
let fileTypes = ["jpg", "jpeg", "bmp", "png", "gif"]
var fileTypeIsOk = false
var droppedFilePath: String?
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
if checkExtension(drag: sender) {
fileTypeIsOk = true
return .copy
} else {
fileTypeIsOk = false
return []
}
}
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
if fileTypeIsOk {
return .copy
} else {
return []
}
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
if let board = sender.draggingPasteboard().propertyList(forType: NSFilenamesPboardType) as? NSArray,
imagePath = board[0] as? String {
// THIS IS WERE YOU GET THE PATH FOR THE DROPPED FILE
droppedFilePath = imagePath
return true
}
return false
}
func checkExtension(drag: NSDraggingInfo) -> Bool {
if let board = drag.draggingPasteboard().propertyList(forType: NSFilenamesPboardType) as? NSArray,
path = board[0] as? String {
let url = NSURL(fileURLWithPath: path)
if let fileExtension = url.pathExtension?.lowercased() {
return fileTypes.contains(fileExtension)
}
}
return false
}
}
This implementation allows for multiple files.
Just set the view class to DragView
in Interface Builder, implement DragViewDelegate
in your controller, then hook up the delegate outlet in Interface Builder. This way you get a delegate callback with the file URLs.
func dragViewDidReceive(fileURLs: [URL])
{
// Yay!
}
DragView.swift
//
// DragView.swift
//
// Copyright (c) 2020 Geri Borbás http://www.twitter.com/_eppz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Cocoa
@objc protocol DragViewDelegate
{
func dragViewDidReceive(fileURLs: [URL])
}
class DragView: NSView
{
@IBOutlet weak var delegate: DragViewDelegate?
let fileExtensions = ["pdf"]
required init?(coder: NSCoder)
{
super.init(coder: coder)
color(to: .clear)
registerForDraggedTypes([.fileURL])
}
override func draggingEntered(_ draggingInfo: NSDraggingInfo) -> NSDragOperation
{
var containsMatchingFiles = false
draggingInfo.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: nil)?.forEach
{
eachObject in
if let eachURL = eachObject as? URL
{
containsMatchingFiles = containsMatchingFiles || fileExtensions.contains(eachURL.pathExtension.lowercased())
if containsMatchingFiles { print(eachURL.path) }
}
}
switch (containsMatchingFiles)
{
case true:
color(to: .secondaryLabelColor)
return .copy
case false:
color(to: .disabledControlTextColor)
return .init()
}
}
override func performDragOperation(_ draggingInfo: NSDraggingInfo) -> Bool
{
// Collect URLs.
var matchingFileURLs: [URL] = []
draggingInfo.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: nil)?.forEach
{
eachObject in
if
let eachURL = eachObject as? URL,
fileExtensions.contains(eachURL.pathExtension.lowercased())
{ matchingFileURLs.append(eachURL) }
}
// Only if any,
guard matchingFileURLs.count > 0
else { return false }
// Pass to delegate.
delegate?.dragViewDidReceive(fileURLs: matchingFileURLs)
return true
}
override func draggingExited(_ sender: NSDraggingInfo?)
{ color(to: .clear) }
override func draggingEnded(_ sender: NSDraggingInfo)
{ color(to: .clear) }
}
extension DragView
{
func color(to color: NSColor)
{
self.wantsLayer = true
self.layer?.backgroundColor = color.cgColor
}
}
Here's an example I'm using in an application.
- Add conformance to
NSDraggingDestination
to your subclass declaration if necessary (not needed forNSImageView
because it already conforms to the protocol) - Declare an array of accepted types (at least
NSFilenamesPboardType
) - Register these types with
registerForDraggedTypes
- Override
draggingEntered
,draggingUpdated
andperformDragOperation
- Return an
NSDragOperation
from these methods - Get the file(s) path(s) from the
draggingPasteboard
array
In my example I've added a function to check if the file extension is amongst the ones we want.
Swift 2
class MyImageView: NSImageView {
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
// Declare and register an array of accepted types
registerForDraggedTypes([NSFilenamesPboardType, NSURLPboardType, NSPasteboardTypeTIFF])
}
let fileTypes = ["jpg", "jpeg", "bmp", "png", "gif"]
var fileTypeIsOk = false
var droppedFilePath: String?
override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation {
if checkExtension(sender) {
fileTypeIsOk = true
return .Copy
} else {
fileTypeIsOk = false
return .None
}
}
override func draggingUpdated(sender: NSDraggingInfo) -> NSDragOperation {
if fileTypeIsOk {
return .Copy
} else {
return .None
}
}
override func performDragOperation(sender: NSDraggingInfo) -> Bool {
if let board = sender.draggingPasteboard().propertyListForType("NSFilenamesPboardType") as? NSArray,
imagePath = board[0] as? String {
// THIS IS WERE YOU GET THE PATH FOR THE DROPPED FILE
droppedFilePath = imagePath
return true
}
return false
}
func checkExtension(drag: NSDraggingInfo) -> Bool {
if let board = drag.draggingPasteboard().propertyListForType("NSFilenamesPboardType") as? NSArray,
path = board[0] as? String {
let url = NSURL(fileURLWithPath: path)
if let fileExtension = url.pathExtension?.lowercaseString {
return fileTypes.contains(fileExtension)
}
}
return false
}
}
Swift 3
class MyImageView: NSImageView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
// Declare and register an array of accepted types
register(forDraggedTypes: [NSFilenamesPboardType, NSURLPboardType, NSPasteboardTypeTIFF])
}
let fileTypes = ["jpg", "jpeg", "bmp", "png", "gif"]
var fileTypeIsOk = false
var droppedFilePath: String?
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
if checkExtension(drag: sender) {
fileTypeIsOk = true
return .copy
} else {
fileTypeIsOk = false
return []
}
}
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
if fileTypeIsOk {
return .copy
} else {
return []
}
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
if let board = sender.draggingPasteboard().propertyList(forType: "NSFilenamesPboardType") as? NSArray,
imagePath = board[0] as? String {
// THIS IS WERE YOU GET THE PATH FOR THE DROPPED FILE
droppedFilePath = imagePath
return true
}
return false
}
func checkExtension(drag: NSDraggingInfo) -> Bool {
if let board = drag.draggingPasteboard().propertyList(forType: "NSFilenamesPboardType") as? NSArray,
path = board[0] as? String {
let url = NSURL(fileURLWithPath: path)
if let fileExtension = url.pathExtension?.lowercased() {
return fileTypes.contains(fileExtension)
}
}
return false
}
}