iOS 长按复制所遇到的坑

1.注册长按手势(我自定义了一个Label,在Label中实现)

  self.userInteractionEnabled = true;
  UILongPressGestureRecognizer * recognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressEvent:)];
 [self addGestureRecognizer:recognizer];

-(void)longPressEvent:(UILongPressGestureRecognizer *)longPress {
    if (longPress.state == UIGestureRecognizerStateBegan) {
        [self becomeFirstResponder];//一定要写
        UIMenuController * menuController = [UIMenuController sharedMenuController];
        [menuController setTargetRect:self.bounds inView:self];
        [menuController setMenuVisible:YES animated:YES];
    }
}

2.设置可为第一响应(别写错了)

- (BOOL)canBecomeFirstResponder{
    return true;
}

3.实现系统相关方法

- (void)copy:(id)sender{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    [pasteboard setString:self.text];
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    return action == @selector(copy:);
}
iOS 长按复制所遇到的坑_第1张图片

系统有对应复制、粘贴、剪切等代理方法,我们只要实现方法就行了,记得在canPerformAction中根据需要添加即可

3.莫名闪退原因(如果你按上面写了但还是会莫名闪退,请看下面)

检查当前界面所属ViewController中有没有你定义为inputView的属性,有请换个名字!!!!!
Over~

你可能感兴趣的:(iOS 长按复制所遇到的坑)