粘貼板提供了一種核心OS特性,用於跨應用程序共享數據。用戶可以跨應用來復制粘貼,也可以設置只在本應用中復制粘貼用來保護隱私。
UIPasteboard類允許訪問共享的設備粘貼板以及內容,下面代碼返回一般的系統粘貼板,它適合大多數一般的復制粘貼應用。
UIPasteboard *pd = [UIPasteboard generalPasteboard];
使用pasteboardWithUniqueName創建特定於應用程序的粘貼板,只有知道並且使用粘貼板名稱鍵的應用程序能能夠使用相同的粘貼板。
使用pasteboardWithName:create:創建自定義的粘貼板,他返回一個具有指定名稱的粘貼板。為粘貼板使用反向DNS命名方法。這種類型的粘貼板可以超越單個應用程序的運行而持續存在;可以再創建后把持久屬性設置為YES。可以使用removePasteboardWithName:銷毀粘貼板,並釋放被他使用的資源。
可以使用UTI指定粘貼板存儲的是那種數據。
可以給粘貼板發送pasteboardType消息,查詢粘貼板的可用類型,這將返回一個數組:
NSArray *types = [pb pasteboardTypes];
可以在粘貼板上設置數據,並通過傳遞一個NSData對象和一個描述數據所順應的類型的UTI
[[UIPasteboard generalPasteboard] setData:theData forPasteboardType:theUTI];
其實在程序開發中,很少用到粘貼板開發,主要是為用戶簡化操作,同時又准備好打算與其他應用程序共享的內容。
下面的例子主要是顯示當在textView中輸入內容,粘貼板自動把輸入內容放入粘貼板,可以通過textview的delegate方法(textViewDidChange:)來完成
- (void) updatePasteboard { if (enableWatcher) [UIPasteboard generalPasteboard].string = textView.text; } - (void)textViewDidChange:(UITextView *)textView { [self updatePasteboard]; } - (void) toggle: (UIBarButtonItem *) bbi { enableWatcher = !enableWatcher; bbi.title = enableWatcher ? @"Stop Watching" : @"Watch"; } - (void) loadView { [super loadView]; self.view.backgroundColor = [UIColor whiteColor]; textView = [[UITextView alloc] initWithFrame:CGRectZero]; textView.delegate = self; [self updatePasteboard]; [self.view addSubview:textView];
