How to copy text to clipboard / cardboard using Swift

I am looking for a clean example of how to copy text to the iOS clipboard, which can then be used / pasted into other applications.

The advantage of this feature is that text can be copied quickly, without the standard text highlighting functions of traditional text copying.

I assume that the key classes are in the UIPasteboard , but cannot find the corresponding areas in the sample code that they provide .

+140
ios cocoa-touch copy swift uipasteboard
Jul 10 '14 at 6:58
source share
5 answers

If you only need plain text, you can simply use the string property . This is for both reading and writing:

 // write to clipboard UIPasteboard.general.string = "Hello world" // read from clipboard let content = UIPasteboard.general.string 

(When reading from the clipboard, the UIPasteboard documentation also suggests that you might want to check hasStrings first, “so as not to force the system to unnecessarily try to retrieve data before it is needed, or when the data may be missing,” for example, when using Distribution .)

+346
Jul 10 '14 at 7:40
source share

Since copying and pasting are usually done in pairs, this is an additional answer to @ jtbandes's nice, concise answer. I originally came here to see how to insert.

iOS makes this easy, because a common dashboard can be used as a variable. Just get and install UIPasteboard.general.string .

Here is an example showing how both are used with a UITextField :

copy

 UIPasteboard.general.string = myTextField.text 

Embed

 if let myString = UIPasteboard.general.string { myTextField.insertText(myString) } 

Note that the line in the pasteboard is optional, so you must expand it first.

+42
Jun 08 '16 at 1:50
source share

Copy text from application to clipboard:

 let pasteboard = UIPasteboard.general pasteboard.string = employee.phoneNumber 
+6
Apr 18 '17 at 11:05
source share

SWIFT 4

 UIPasteboard.general.string = "TEXT" 
+3
Apr 29 '19 at 23:43 on
source share

SWIFT 4

 func copyToClipBoard(textToCopy: String) { UIPasteboard.general.string = "" UIPasteboard.general.string = textToCopy } 

name it as below where you want to copy

 self.copyToClipBoard("Text you want to copied to clipboard") 
0
Jan 18 '19 at 11:36
source share



All Articles