6

我正在尝试在 iPhone 粘贴板中添加一些纯文本。以下代码似乎不起作用:

UIPasteboard *pboard = [UIPasteboard generalPasteboard];
NSString *value = @"test";
[pboard setValue: value forPasteboardType: @"public.plain-text"];

我猜问题出在 PasteBoard 类型参数中。通过@"public.plain-text"什么都不会发生。通过kUTTypePlainText编译器会抱怨指针类型不兼容,但不会崩溃,也没有任何反应。使用kUTTypePlainText似乎也需要与 链接MobileCoreServices,这在文档中没有提到。

4

3 回答 3

19

使用此标头获取 kUTTypeUTF8PlainText 的值;

#import <MobileCoreServices/UTCoreTypes.h>

您需要有可用的 MobileCoreServices 框架。

于 2009-07-14T20:27:02.863 回答
8

回应评论和我自己的问题:

  • 设置pasteboard字符串属性有效。
  • setValue:forPasteboardType:如果我使用kUTTypeUTF8PlainText而不是kUTTypePlainText粘贴板类型,则使用也有效。

我没有注意到字符串属性,因为我直接进入了“获取和设置单个粘贴板项目”任务部分。

我测试的方法是单击文本字段,看看是否会出现粘贴弹出窗口。

我仍然不确定文档在哪里解释了 iPhone 的 UTT 类型,包括从哪里获取它们(框架、#include文件),似乎“统一类型标识符概述”文档仍然面向 Mac OS。由于常量给了我一个类型不匹配的警告,我认为我做错了什么,这就是我第一次尝试使用NSString文字的原因。

于 2009-06-29T13:12:47.853 回答
3

这是我将文本粘贴到粘贴板上的实验。我正在使用一个按钮以编程方式添加文本。

#import <MobileCoreServices/MobileCoreServices.h>

- (IBAction)setPasteboardText:(id)sender
{
    UIPasteboard *pb = [UIPasteboard generalPasteboard];
    NSString *text = @"東京京都大阪";

    // Works, but generates an incompatible pointer warning
    [pb setValue:text forPasteboardType:kUTTypeText];

    // Puts generic item (not text type), can't be pasted into a text field
    [pb setValue:text forPasteboardType:(NSString *)kUTTypeItem];

    // Works, even with non-ASCII text
    // I would say this is the best way to do it with unknown text
    [pb setValue:text forPasteboardType:(NSString *)kUTTypeText];

    // Works without warning
    // This would be my preferred method with UTF-8 text
    [pb setValue:text forPasteboardType:(NSString *)kUTTypeUTF8PlainText];

    // Works without warning, even with Japanese characters
    [pb setValue:text forPasteboardType:@"public.plain-text"];

    // Works without warning, even with Japanese characters
    [pb setValue:text forPasteboardType:@"public.text"];

    // Check contents and content type of pasteboard
    NSLog(@"%@", [pb items]);
}

我将内容粘贴到文本字段中进行检查,并每次更改文本内容以确保它不只是重复使用以前的粘贴。

于 2012-10-25T13:16:01.567 回答