cocoa - 使用UTI而不是NSFileContentsPboardType将文件内容放在NSPasteboard上?

标签 cocoa clipboard nspasteboard uti

我有包含一些图像和文本的富文本文件。在我的 Cocoa 应用程序中,我尝试将该文件的内容放在 NSDragPboard 上,以便用户可以将内容拖到其他应用程序(TextEdit、Mail 等)中。 )。

一个用例是这样的:富文本文件包含电子邮件模板,用户将内容拖到新的邮件消息中。

我尝试过但没有成功:

NSPasteboard *pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
[pboard writeFileContents:filePath];

Apple 文档是这样说的:

Writes the contents of the file filename to the receiver and declares the data to be of type NSFileContentsPboardType and also of a type appropriate for the file’s extension (as returned by the NSCreateFileContentsPboardType function when passed the files extension), if it has one.

在 ClipboardViewer 应用程序中,我可以看到一些数据类型,其中之一是 NXFileContentsPboardType。但是,Mail 和 TextEdit 等应用程序不允许删除该数据类型。

当我手动将富文本内容复制到剪贴板 (Control+C) 时,我看到了所需的所有不同数据类型:

  • public.rtf
  • public.utf8-plain-text
  • NSStringPboardType
  • ...

那么我怎样才能自己以编程方式做到这一点呢?我是否必须弄清楚所有各种尿路感染类型并设置相应的数据?我认为这就是 [pboard writeFileContents:path] 的用途...

谢谢,马克。

编辑:

取得进展...这适用于 .rtf 文件,但不适用于 .txt 文件:

NSString *uti = // helper code to get UTI from NSURL resource key...
NSPasteboard *pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
[pboard declareTypes:[NSArray arrayWithObject:uti] owner:nil];
[pboard setData:[NSData dataWithContentsOfFile:filePath] forType:uti];

对于 .txt 文件,粘贴板上的数据类型为 public.text。但是,TextEdit 和 Mail.app 不允许删除该类型。 public.rtf 在富文本的情况下工作正常...

最佳答案

看起来无法将文件内容添加到粘贴板并自动检测内容类型。

事实证明,将 RTF/RTFD 文件内容放在粘贴板上非常简单:

NSAttributedString *contents = [[NSAttributedString alloc] initWithPath:filePath documentAttributes:NULL];
// This sets the correct type automatically:
[pboard writeObjects:[NSArray arrayWithObject:contents]];
[contents release];

关于cocoa - 使用UTI而不是NSFileContentsPboardType将文件内容放在NSPasteboard上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6030240/

相关文章:

objective-c - 在 mac os x app cocoa 中生成图像文件的问题

objective-c - 如何让NSProgressIndicator(进度条)从0慢慢填充到100?

objective-c - 如何复制CGLayer

java - 程序退出时清除 JTextArea.copy() 剪贴板

javascript - 在 Node.js 中复制到剪贴板?

cocoa - 如何先保存粘贴板内容然后再恢复它们?

cocoa - 从 Cocoa 中的任何地方引用对象

javascript - 在 Chrome 中使用 jQuery/js 复制到剪贴板

cocoa - 将字符串数组发送到 NSPasteBoard

objective-c - cocoa:拖放 svg 图像