2012-01-20 55 views
6

快速簡單的問題的iOS - 檢測當用戶複製到剪貼板 - [UIPasteboard generalPasteboard]

而使用的WebView在一些文本 - 用戶可以從它 選擇中的一段文字,然後按一個UIButton我創建 - 運行以下動作:

-(IBAction)copyToClip 
{ 
    NSString *copyClip = [UIPasteboard generalPasteboard].string; 
    NSLog(@"Clip = %@",copyClip); 
    // (works fine) 
} 

我想調用相同的功能,無需一個UIButton,因此當用戶做了一個「複製」操作會激活上面的代碼。 (我假設聽衆)

什麼是適當的聽衆?

+0

你檢查這些通知:HTTP://stackoverflow.com/questions/4240087/receiving-uipasteboard-generalpasteboard-notification-while-in-the -背景 ? –

回答

9

使用NSNotificationCenter並註冊UIPasteboardChangedNotification: http://developer.apple.com/library/IOs/documentation/UIKit/Reference/UIPasteboard_Class/Reference.html#//apple_ref/c/data/UIPasteboardChangedNotification

[[NSNotificationCenter defaultCenter] addObserver:object selector:@selector(copyToClip) name:UIPasteboardChangedNotification object:nil]; 
+1

謝謝!工作得很好。 – chewy

+1

嘿,當用戶在任何其他應用程序中複製任何內容時它工作嗎? –