Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Building an OSX Drag and Drop Playground: Throw the dragndrop.swift into shared Sources and then test out the examples in individual playgrounds. Make sure the assistant is open and set to the timeline. I prefer vertical assistant stacking for this.
import Cocoa
// Support Foundation calls on String
public extension String { public var ns: NSString {return self as NSString} }
/// Custom Labeled Playground-Based Drag-and-Drop window
public class DropView: NSTextField {
// Default action handler
public var handler: ([String]) -> Void = { paths in Swift.print(paths) }
// Drag and drop notification
public override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation { return NSDragOperation.Copy }
public override func draggingUpdated(sender: NSDraggingInfo) -> NSDragOperation { return NSDragOperation.Copy }
public override func performDragOperation(sender: NSDraggingInfo) -> Bool {
let pboard = sender.draggingPasteboard()
guard let paths = pboard.propertyListForType(NSFilenamesPboardType) as? [String] else { return false }
handler(paths)
return true
}
public required init?(coder: NSCoder) { super.init(coder: coder) }
public override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
// Presentation
stringValue = "Drop Here"; editable = false
font = NSFont(name: "Palatino", size: 48.0); alignment = .Center
wantsLayer = true; layer?.backgroundColor = NSColor.whiteColor().CGColor
// Register for file name drags
registerForDraggedTypes([NSFilenamesPboardType])
}
}
import Cocoa
import XCPlayground
// Establish drop view
let dropView = DropView(frame: NSRect(x: 0, y: 0, width: 600, height: 200))
dropView.stringValue = "Drop text files here for word counts"
dropView.handler = {
print("Word Counts")
for path in $0 {
guard let string = try? String(contentsOfFile: path) else { continue }
print(path.ns.lastPathComponent, ":",
string.ns.componentsSeparatedByString(" ").count)
}
}
// Run live
XCPlaygroundPage.currentPage.liveView = dropView
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
import Cocoa
import XCPlayground
// Establish drop view
let dropView = DropView(frame: NSRect(x: 0, y: 0, width: 600, height: 200))
dropView.stringValue = "Drop Pictures"
dropView.handler = {
// Print out each file name and image size
$0.forEach {
if let image = NSImage(contentsOfFile: $0) {
Swift.print($0.ns.lastPathComponent, image.size)
} else {
Swift.print($0.ns.lastPathComponent, "is not an image")
}
}
}
// Run live
XCPlaygroundPage.currentPage.liveView = dropView
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment