I\'m a beginner with Swift, and I\'m trying to figure out how can I read what has been copied to the clipboard On macOS (Swift 3)? I\'ve searched a lot but can\'t seem to find a
Another solution.
class ViewController : NSViewController {
@IBAction func pasteMenuItemAction(_ sender: NSMenuItem) {
let p = NSPasteboard.general
let x = p.readObjects(forClasses: [NSString.self], options: nil)
let s = x as! [NSString]
if 0 < s.count {
print(s[0])
}
}
}
That func pasteMenuItemAction()
is bound to an Edit > Paste menu item.
I use writeObjects()
for Edit > Copy. So it is natural for me to use its counterpart readObjects()
here.
Confirmed with Xcode 9.2, Swift 4
Added:
One of the solutions for Edit > Copy:
@IBAction func copyMenuItemAction(_ sender: NSMenuItem) {
let t = "Hello!"
let p = NSPasteboard.general
p.clearContents()
p.writeObjects([t as NSPasteboardWriting])
}
That func copyMenuItemAction()
is bound to an Edit > Copy menu item.