在iPhone上使用多种数据表示方式进行复制和粘贴

10

在尝试将多个数据表示粘贴到 iPhone 3.0 上的剪贴板时,我遇到了一些问题。

我的目标是将一个数据表示和一个字符串表示放到剪贴板上。这个数据类型是我自己定义的,并且用于在应用程序中进行复制和粘贴。字符串表示是一种将我的应用程序内容作为大纲复制并粘贴到其他应用程序(例如 Mail.app)中的方法。

    // payload
NSString *pasteboardString = [selectedNode stringRepresentation];
NSDictionary *pasteboardDictionary = [selectedNode nodeAndSubnodesProperties];

// set payload
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = pasteboardString;
[pasteboard setValue:pasteboardDictionary forPasteboardType:MNTNodesPasteboardType];

上面的代码不起作用是因为字符串属性和setValue:forPasteboardType:方法会替换剪贴板上的第一个表示。我尝试了addItems:但对我没有用。

感谢任何帮助!

2个回答

18
回答自己的问题:
必须使用 "items" 属性将多个表示形式放入剪贴板。为此,创建一个字典,其中每个表示形式都是值,表示类型是键。将该字典添加到一个数组中,其中数组中的每个项表示一个项目(UIPasteboard 支持将多个项目添加到剪贴板以及向每个项目添加多个表示形式)。
以下是一个包含两个表示形式的单个项目的示例代码:
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
NSMutableDictionary *item = [NSMutableDictionary dictionaryWithCapacity:2];
[item setValue:[NSKeyedArchiver archivedDataWithRootObject:pasteboardDictionary] forKey:MNTNodesPasteboardType];
[item setValue:pasteboardString forKey:(NSString *)kUTTypeUTF8PlainText];
pasteboard.items = [NSArray arrayWithObject:item];

别忘了链接MobileCoreServices框架以解决UTI常量。


0

这是我在Swift中使用的方法,它可以将图像和文本一起复制到剪贴板中。

let pastebaord = UIPasteboard.generalPasteboard()
let image = UIImage(named: "my-image-file")
pastebaord.addItems([ [UIPasteboardTypeListString[0] as! String : "hello"], [UIPasteboardTypeListImage[0] as! String: image!]]) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接