清除UIPasteBoard

时间:2016-04-03 10:48:45

标签: swift uipasteboard

让我们假设在UIPasteBoard上复制了3个字符串:

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

我用     。UIPasteboard.generalPasteboard()字符串=""

它会清除粘贴板吗?对于UIPasteBoard有没有类似的函数,就像NSPasteBoard有clearContents()一样?

1 个答案:

答案 0 :(得分:4)

如果您知道您的程序是唯一操作特定粘贴板的程序,那么将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属性是第一个类型为string的粘贴板项的简写。可以通过strings属性访问字符串类型的所有项目。

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

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

UIPasteboard.generalPasteboard().items = []

如果您将粘贴板用于内部应用程序,则最好创建内部粘贴板,而不是使用系统范围的generalPasteboard。见pasteboardWithUniqueName()