代碼
- (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 = @"據(jù)說這是馬化騰親自敲的";
? ? 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;
}
//設(shè)置可彈出的菜單
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
if (action == @selector(copyContent:){
? ? ? ? //自定義的
? ? ? ? return YES;
}else if (action == @selector(cut:) || action == @selector(copy:) || action == @selector(paste:)){? ?
? ? ? ? //系統(tǒng)的,默認(rèn)返回NO
? ? ? ? return YES;
}
? ? return [super canPerformAction:action withSender:sender];
}
// 長按彈出菜單并添加自定義菜單。
- (void)longTapClick:(UILongPressGestureRecognizer *)recognizer{
? ? [self becomeFirstResponder];
? ? UIMenuItem *copyLink = [[UIMenuItem alloc] initWithTitle:@"復(fù)制" action:@selector(copyContent:)];
? ? [UIMenuController sharedMenuController].menuItems = @[copyLink];
? ? [[UIMenuController sharedMenuController] setTargetRect:self.testLabel.frame inView:self.testLabel.superview];
? ? [[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
}
//自定義方法實(shí)現(xiàn)
- (void)copyContent:(id)sender{
? ? UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
? ? pasteBoard.string = self.testLabel.text;
}
//系統(tǒng)三方法實(shí)現(xiàn)
- (void)cut:(UIMenuController *)menu {
? ? //剪切
? ? [self copy:menu];
? ? self.testLabel.text = nil;
}
- (void)copy:(UIMenuController *)menu {
? ? // 復(fù)制
? ? UIPasteboard *board = [UIPasteboard generalPasteboard];
? ? board.string = self.testLabel.text;
}
- (void)paste:(UIMenuController *)menu {
? ? // 粘貼
? ? UIPasteboard *board = [UIPasteboard generalPasteboard];
? ? self.testLabel.text = board.string;
}
效果圖
