2009-06-28 39 views
6

我試圖在iPhone粘貼板上放一些純文本。下面的代碼似乎不工作:基本的iPhone粘貼板的使用

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

我猜問題是在PasteBoard類型的參數。通過@"public.plain-text"沒有任何反應。傳遞kUTTypePlainText編譯器抱怨指針類型不兼容,但不會崩潰,也沒有任何反應。使用kUTTypePlainText似乎也需要鏈接MobileCoreServices,這在文檔中未提及。

+2

我可以問爲什麼你這樣做而不是使用 - [UIPasteboard setString:]方法?另外,你什麼意思是「什麼都沒有發生?」你期待什麼發生?你怎麼確定這個? – 2009-06-29 11:08:30

回答

8

應對的意見和我自己的問題:

  • 設置pasteboard字符串屬性的作品。
  • 如果我使用kUTTypeUTF8PlainText而不是kUTTypePlainText作爲粘貼板類型,則使用setValue:forPasteboardType:也可以。

我沒有注意到字符串屬性,因爲我直接去了「獲取和設置單紙板項目」任務部分。

我測試的方式是通過單擊文本字段並查看是否顯示粘貼彈出窗口。

我仍然不確定在文檔中爲iPhone解釋了UTT類型,包括在哪裏獲取它們(Framework,#include文件),似乎「統一類型標識符概述」文檔仍然適用於Mac OS。由於常量給了我一個類型不匹配警告,我認爲我做錯了,這就是爲什麼我第一次嘗試使用NSString文字。

+1

正如我所解釋的那樣,它與面向Mac OS X的操作無關,您只需要投射字符串即可。這些常量被聲明爲CFStringRef,它是與NSString橋接的tollfree。只要做:(NSString *)kUTTypePlainText – 2009-06-30 09:47:14

19

使用此標題獲取kUTTypeUTF8PlainText的值;

#import <MobileCoreServices/UTCoreTypes.h> 

您需要有MobileCoreServices框架可用。

+3

實現只是爲了讓它看起來很清楚:`[pboard setValue:value forPasteboardType:(NSString *)kUTTypeUTF8PlainText];` – 2012-08-08 09:47:56

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]); 
} 

我粘貼內容到一個文本字段,檢查,每一次,以確保以前的貼吧不只是重新使用改變了文本內容。

+0

如果我想要粘貼圖像,我該怎麼辦? – Ramakrishna 2016-10-13 05:45:56

相關問題