iOS Label 长按拷贝、粘贴、剪切的实现

代码如下(这里是延展的 .m 文件中实现部分):

@implementation CustomEditLabel

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)awakeFromNib{
    [super awakeFromNib];
    
    [self addLongPressEvent];
}
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {

        [self addLongPressEvent];
    }
    return self;
}

- (void)addLongPressEvent{
    
    self.userInteractionEnabled = YES;
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(actionS:)];
    [self addGestureRecognizer:longPress];
    
}


- (void)actionS:(UILongPressGestureRecognizer *)gesture{
    
    if (gesture.state == UIGestureRecognizerStateBegan) {
    
    [self becomeFirstResponder];
    UIMenuItem *menuItem1 = [[UIMenuItem alloc] initWithTitle:@"拷贝哦" action:@selector(copyS:)];
    UIMenuItem *menuItem2 = [[UIMenuItem alloc] initWithTitle:@"粘贴哦" action:@selector(pasteS:)];
    UIMenuItem *menuItem3 = [[UIMenuItem alloc] initWithTitle:@"剪切哦" action:@selector(cutS:)];
    UIMenuController *menuC = [UIMenuController sharedMenuController];

    menuC.menuItems = @[menuItem1, menuItem2, menuItem3];
    menuC.arrowDirection = UIMenuControllerArrowUp;
    
    if (menuC.menuVisible) {
//        NSLog(@"menuC.menuVisible    判断 --  %d", menuC.menuVisible);
        return ;
    }
    
    [menuC setTargetRect:self.frame inView:self.superview];
    [menuC setMenuVisible:YES animated:YES];
        
   }
}

- (BOOL)canBecomeFirstResponder{
    return YES;
    
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    
    if ( action == @selector(copyS:)  || (action == @selector(pasteS:) && [UIPasteboard generalPasteboard].string) || action == @selector(cutS:) ) {
//        NSLog(@"粘贴板   --  %@", [UIPasteboard generalPasteboard].string);
        return YES;
    }else{
        return NO;
    }
}
//剪切事件(暂时不用)
- (void)cutS:(id)sender{
    
    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    pboard.string = self.text;
    //剪切 功能
    self.text = nil;
}

//拷贝
- (void)copyS:(id)sender{
    
    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    pboard.string = self.text;
    
}
//粘贴
- (void)pasteS:(id)sender{
    
    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    self.text = pboard.string;
}


@end

有不完整的地方请多多指教 。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,686评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 好久没有写文章了,想记录下自从15年毕业到如今17年在深圳的点点滴滴。 生活犹如一碗酸甜苦辣的水,我本是一个自私透...
    艾瑞巴蒂的粑粑阅读 179评论 0 1
  • 吾心愿为父母令,自己作诗众人醒。 看破天下如做帽,一切只想忠情晶。
    乱花渐欲迷人眼阅读 164评论 0 0