How to copy text to clipboard/pasteboard with Swift

你离开我真会死。 提交于 2019-11-28 16:07:49

If all you want is plain text, you can just use the string property. It's both readable and writable:

// 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 you might want to first check hasStrings, "to avoid causing the system to needlessly attempt to fetch data before it is needed or when the data might not be present", such as when using Handoff.)

Since copying and pasting is usually done in pairs, this is supplemental answer to @jtbandes good, concise answer. I originally came here looking how to paste.

iOS makes this easy because the general pasteboard can be used like a variable. Just get and set UIPasteboard.general.string.

Here is an example showing both being used with a UITextField:

Copy

UIPasteboard.general.string = myTextField.text

Paste

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

Note that the pasteboard string is an Optional, so it has to be unwrapped first.

Raj Joshi

Copying text from the app to the clipboard:

let pasteboard = UIPasteboard.general
pasteboard.string = employee.phoneNumber

SWIFT 4

UIPasteboard.general.string = "TEXT"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!