iOS - 检测用户何时复制到剪贴板 - [UIPasteboard generalPasteboard]

che*_*ewy 8 iphone copy-paste objective-c uipasteboard ios

快速简单的问题

当使用带有一些文本的WebView时 - 用户可以从中选择一段文本并按下我创建的UIButton - 运行以下操作:

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

我想在没有UIButton的情况下调用相同的函数,因此当用户执行"复制"操作时,它将激活上面的代码.(我假设是听众)

什么是适当的听众?

小智 12

使用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];
Run Code Online (Sandbox Code Playgroud)

  • 嘿,当用户在任何其他应用程序中复制任何东西时它是否正常工作. (2认同)