Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy textField to OSX clipboard?

I'm stuck here. I know how to copy and paste on the iPhone side of things but how can I copy contents from a textField to the global clipboard in OSX. I've been searching the web but there are really no examples. So let me explain in detail what I'm trying to accomplish. I have a NSTextField named helloField and I want to be able to copy the contents of this helloField to the global pasteboard by pressing a button. How can this be done and is there certain libraries I need? Thanks.

like image 393
0SX Avatar asked Sep 07 '10 00:09

0SX


People also ask

Is there copy and paste for Macbook?

To quickly reuse text, copy it in one location and paste it to another. Select the text to copy. Choose Edit > Copy (from the Edit menu at the top of your screen), or press Command-C. Note: If you want to remove the text from its original location, choose Edit > Cut instead.

How do I copy and paste on a Mac?

Command-C Copy the selected item to the Clipboard. This also works for files in the Finder. Command-V Paste the contents of the Clipboard into the current document or app. This also works for files in the Finder.


2 Answers

On iOS

[UIPasteboard generalPasteboard].string = helloField.text;

On OSX

[[NSPasteboard generalPasteboard] clearContents];
[[NSPasteboard generalPasteboard] setString:helloField.stringValue forType:NSStringPboardType];

On macOS and Swift 3.x

let pasteBoard = NSPasteboard.general()
pasteBoard.clearContents()
pasteBoard.writeObjects([text as NSString])
like image 136
erkanyildiz Avatar answered Oct 25 '22 07:10

erkanyildiz


For Swift 5

let pasteboard = NSPasteboard.general
pasteboard.clearContents()
pasteboard.setString("string to copy", forType: .string)
like image 43
Jay Mehta Avatar answered Oct 25 '22 08:10

Jay Mehta