在开发过程中,只有UITextView,UITextField,和UIWebView才能调用剪贴板,其它控件的剪贴板都被禁用了,要让其他控件也能实现剪贴板的功能,就需要手动实现剪贴板的功能。(这里拿UILabel为例子)
首先需要创建一个类,继承于UILabel。
然后实现以下三个方法:
- (id)init
{
self = [super init];
if (self) {
[self attachTapHandler];
}
return self;
}
// 可以成为第一响应者
- (BOOL)canBecomeFirstResponder
{
return YES;
}
// 打开你需要的功能, 这里打开了copy,paste,cut,select,delete
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(copy:)) {
return YES;
}
if (action == @selector(paste:)) {
return YES;
}
if (action == @selector(cut:)) {
return YES;
}
if (action == @selector(select:)) {
return YES;
}
if (action == @selector(delete:)) {
return YES;
}
return NO;
}
// Label默认是不接收事件的,这里我们给label添加长按手势(在init方法中调用该方法)
- (void)attachTapHandler
{
self.userInteractionEnabled = YES; // 用户交互的总开关
// 初始化一个长按手势,长按时间为0.8f秒
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
longPress.minimumPressDuration = 0.8f;
[self addGestureRecognizer:longPress];
}
// 长按手势的响应事件
- (void)longPress:(UILongPressGestureRecognizer *)ges
{
if (ges.state == UIGestureRecognizerStateBegan) { // 长按手势出发时执行
[self becomeFirstResponder]; // 让Label成为第一响应者
// 创建衣蛾UIMenuController对象
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setTargetRect:self.frame inView:self.superview];
[menu setMenuVisible:YES animated:YES];
}
}
// 实现copy功能
- (void)copy:(id)sender
{
// 获取系统剪贴板,并将Label上得文字存入剪贴板中
UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
pasteBoard.string = self.text;
}
// 实现paste功能
- (void)copy:(id)sender
{
// 获取系统剪贴板,pasteBoard.string即为剪贴板中得内容
UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
NSLog(@"%@",pasteBoard.string);
}