代码
- (void)viewDidLoad {
[super viewDidLoad];
[self createLabel];
}
- (void)createLabel {
self.testLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 200, 200, 20)];
self.testLabel.backgroundColor = [UIColor yellowColor];
self.testLabel.text = @"据说这是马化腾亲自敲的";
self.testLabel.userInteractionEnabled = YES;
UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTapClick:)];
[self.testLabel addGestureRecognizer:longTap];
[self.view addSubview:self.testLabel];
}
//允许弹出菜单
- (BOOL)canBecomeFirstResponder{
return YES;
}
//设置可弹出的菜单
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
if (action == @selector(copyContent:){
//自定义的
return YES;
}else if (action == @selector(cut:) || action == @selector(copy:) || action == @selector(paste:)){
//系统的,默认返回NO
return YES;
}
return [super canPerformAction:action withSender:sender];
}
// 长按弹出菜单并添加自定义菜单。
- (void)longTapClick:(UILongPressGestureRecognizer *)recognizer{
[self becomeFirstResponder];
UIMenuItem *copyLink = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyContent:)];
[UIMenuController sharedMenuController].menuItems = @[copyLink];
[[UIMenuController sharedMenuController] setTargetRect:self.testLabel.frame inView:self.testLabel.superview];
[[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
}
//自定义方法实现
- (void)copyContent:(id)sender{
UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
pasteBoard.string = self.testLabel.text;
}
//系统三方法实现
- (void)cut:(UIMenuController *)menu {
//剪切
[self copy:menu];
self.testLabel.text = nil;
}
- (void)copy:(UIMenuController *)menu {
// 复制
UIPasteboard *board = [UIPasteboard generalPasteboard];
board.string = self.testLabel.text;
}
- (void)paste:(UIMenuController *)menu {
// 粘贴
UIPasteboard *board = [UIPasteboard generalPasteboard];
self.testLabel.text = board.string;
}