清除 UIPasteBoard

Clear UIPasteBoard

假设已在 UIPasteBoard 上复制了 3 个字符串:

UIPasteboard.generalPasteboard().string="hello"
UIPasteboard.generalPasteboard().string="world"
UIPasteboard.generalPasteboard().string="!"

我用 UIPasteboard.generalPasteboard().string=""

它会清除粘贴板吗? UIPasteBoard 是否有类似的功能,就像 NSPasteBoard 有 clearContents() 一样?

如果您知道您的程序是唯一一个操作特定粘贴板的程序,那么是的,将 string 属性 设置为 "" 将有效地清除粘贴板。

您可以在 Playground 中轻松测试它

var pb = UIPasteboard.generalPasteboard()
pb.string = "hello"
pb.string
pb.items
pb.string = ""
pb.string   
pb.items

输出

<UIPasteboard: 0x7fed6bd0a750>
<UIPasteboard: 0x7fed6bd0a750>
"hello"
[["public.utf8-plain-text": "hello"]]
<UIPasteboard: 0x7fed6bd0a750>
nil
[[:]]

但是,请注意 UIPasteboard 的 string 属性 是第一个字符串类型的粘贴板项目的 shorthand。所有字符串类型的项都可以通过strings 属性.

访问

所有底层粘贴板项目都在 items 属性 中建模,这是一个 [String: AnyObject] 类型的字典数组。每个字典在键中包含对象的类型信息,在值中包含粘贴板值。

因为您使用的是系统范围的 generalPasteboard,它也可以被其他程序操作,因此,要清除粘贴板中的所有项目,您应该使用

UIPasteboard.generalPasteboard().items = []

如果您将粘贴板用于内部应用程序,创建内部粘贴板比使用系统范围的通用粘贴板更好。参见 pasteboardWithUniqueName()