ios 如何使用 Swift 将文本复制到剪贴板/粘贴板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24670290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to copy text to clipboard/pasteboard with Swift
提问by Garry Law
I'm looking for a clean example of how to copy text to iOS clipboard that can then be used/pasted in other apps.
我正在寻找一个干净的示例,说明如何将文本复制到 iOS 剪贴板,然后可以在其他应用程序中使用/粘贴。
The benefit of this function is that the text can be copied quickly, without the standard text highlighting functions of the traditional text copying.
此功能的好处是可以快速复制文本,无需传统文本复制的标准文本突出显示功能。
I am assuming that the key classes are in UIPasteboard
, but can't find the relevant areas in the code example they supply.
回答by jtbandes
If all you want is plain text, you can just use the string
property. It's both readable and writable:
如果你想要的只是纯文本,你可以只使用string
属性。它既可读又可写:
// write to clipboard
UIPasteboard.general.string = "Hello world"
// read from clipboard
let content = UIPasteboard.general.string
(When readingfrom the clipboard, the UIPasteboard documentationalso 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.)
(从剪贴板读取时,UIPasteboard 文档还建议您可能首先检查hasStrings
,“以避免导致系统在需要之前或数据可能不存在时不必要地尝试获取数据”,例如在使用 Handoff 时.)
回答by Suragch
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.
由于复制和粘贴通常是成对完成的,因此这是对@jtbandes 好的简洁答案的补充答案。我最初是来这里看如何粘贴的。
iOS makes this easy because the general pasteboard can be used like a variable. Just get and set UIPasteboard.general.string
.
iOS 使这变得简单,因为通用粘贴板可以像变量一样使用。只需获取并设置UIPasteboard.general.string
。
Here is an example showing both being used with a UITextField
:
这是一个示例,显示两者都与 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.
请注意,粘贴板字符串是一个 Optional,因此必须先对其进行解包。
回答by Raj Joshi
Copying text from the app to the clipboard:
将文本从应用程序复制到剪贴板:
let pasteboard = UIPasteboard.general
pasteboard.string = employee.phoneNumber
回答by álvaro Agüero
SWIFT 4
快速 4
UIPasteboard.general.string = "TEXT"