label实现复制功能,通过子类实现的,当然也可以用分类
#import "YJCLabel.h" @implementation YJCLabel - (void)awakeFromNib{ [super awakeFromNib]; [self addLongGR]; } - (instancetype)initWithFrame:(CGRect)frame{ if (self = [super initWithFrame:frame]) { [self addLongGR]; } return self; } - (instancetype)init{ if (self = [super init]) { [self addLongGR]; } return self; } //添加长按手势 - (void)addLongGR{ self.userInteractionEnabled = YES; UILongPressGestureRecognizer *lpr = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressGR:)]; [self addGestureRecognizer:lpr]; } //长按手势实现 -(void)longPressGR:(UIGestureRecognizer*) recognizer { [self becomeFirstResponder]; UIMenuItem *copyItem = [[UIMenuItem alloc]initWithTitle:@"复制" action:@selector(copyText:)];//注意名字不能与系统默认的copy相同,要不然会显示一个title为copy的item UIMenuItem *pasteItem = [[UIMenuItem alloc]initWithTitle:@"粘贴" action:@selector(pasteText:)]; [[UIMenuController sharedMenuController] setMenuItems:@[copyItem,pasteItem]];//这儿需要判断一下粘贴板有没有文字,哈哈偷懒 [[UIMenuController sharedMenuController]setTargetRect:self.frame inView:self.superview];//还有个menuFrame属性 [[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES]; } //复制文本 - (void)copyText:(id)sender{ [UIPasteboard generalPasteboard].string = self.text; } //粘贴文本 - (void)pasteText:(id)sender{ self.text = [UIPasteboard generalPasteboard].string; } //允许成为第一响应者,默认NO - (BOOL)canBecomeFirstResponder{ return YES; } //判断操作是不是自己想要的 - (BOOL)canPerformAction:(SEL)action withSender:(id)sender{ return (action == @selector(copyText:) || action == @selector(pasteText:)); } @end
注意与表类族之间的响应交换,如果没有特殊的要求,还是用textView吧哈哈