美文网首页
UILabel+CopyLabelText

UILabel+CopyLabelText

作者: 我的马里奥兄弟 | 来源:发表于2017-03-02 11:20 被阅读71次

说明:这是一个带长按复制功能的Label扩展

前按:实现该功能需要用到的类有,UIMenuItem、UIMenuController、UIPasteboard。

代码:

//  .h文件

#import@interface UILabel (CopyLabel)

- (void)copyLabelText;

@end

- (void)copyLabelText{

    [self setUp];

}

- (void)setUp{

    self.userInteractionEnabled = YES;

[self addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self     action:@selector(longPressAction:)]];

}

- (void)longPressAction:(UILongPressGestureRecognizer *)press{

//设置为第一响应,通过第一响应者UIMenuController可以获得支持那些操作信息

    [self becomeFirstResponder];

    UIMenuController *menu = [UIMenuController sharedMenuController];

    UIMenuItem *copyMenu = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyMenuAction)];

    menu.menuItems = @[copyMenu];

    [menu setTargetRect:self.bounds inView:self];

     [menu setMenuVisible:YES animated:YES];

}

- (void)copyMenuAction{

     if (!self.text) return;

     UIPasteboard *paste = [UIPasteboard generalPasteboard];

     paste.string = self.text;

}

// 用于UIMenuController显示,缺一不可

-(BOOL)canBecomeFirstResponder{

     return YES;

}

// 用于UIMenuController显示,缺一不可

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{

     if (action == @selector(copyMenuAction)){

              return YES;

     }

     return NO;//隐藏系统默认的菜单项

}

相关文章

  • UILabel+CopyLabelText

    说明:这是一个带长按复制功能的Label扩展 前按:实现该功能需要用到的类有,UIMenuItem、UIMenuC...

网友评论

      本文标题:UILabel+CopyLabelText

      本文链接:https://www.haomeiwen.com/subject/nwyhgttx.html