清除 UIPasteBoard

Do2*_*Do2 3 uipasteboard swift

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

UIPasteboard.generalPasteboard().string="hello"
UIPasteboard.generalPasteboard().string="world"
UIPasteboard.generalPasteboard().string="!"
Run Code Online (Sandbox Code Playgroud)

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

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

Tee*_*ppa 10

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

您可以在 Playground 中轻松测试

var pb = UIPasteboard.generalPasteboard()
pb.string = "hello"
pb.string
pb.items
pb.string = ""
pb.string   
pb.items
Run Code Online (Sandbox Code Playgroud)

哪个输出

<UIPasteboard: 0x7fed6bd0a750>
<UIPasteboard: 0x7fed6bd0a750>
"hello"
[["public.utf8-plain-text": "hello"]]
<UIPasteboard: 0x7fed6bd0a750>
nil
[[:]]
Run Code Online (Sandbox Code Playgroud)

但是,请注意stringUIPasteboard 的属性是第一个字符串类型的粘贴板项目的简写。字符串类型的所有项目都可以通过strings属性访问。

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

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

UIPasteboard.generalPasteboard().items = []
Run Code Online (Sandbox Code Playgroud)

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

  • 不,您的解决方案只会清除第一个粘贴板字符串项目。如果要清除所有字符串,可以尝试`pb.strings = []`。 (2认同)