最近项目开发中遇到要复制Label上的文字的需求,经过查阅资料整理开发。
下面是自己借鉴网上各位大神的方法实现自己的需求。
首先,创建自定义Label 集成UILabel
#import@interface LRCopyLabel : UILabel
@end
接着实现具体方法
@implementation LRCopyLabel
//拖拽
-(void)awakeFromNib {
[super awakeFromNib];
[self addLongPressGesture];
}
//手动创建
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
[self addLongPressGesture];
}
return self;
}
//添加长按手势
- (void)addLongPressGesture {
self.userInteractionEnabled = YES;
UILongPressGestureRecognizer * longGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longAction:)];
[self addGestureRecognizer:longGesture];
}
//长按触发的事件
- (void)longAction:(UILongPressGestureRecognizer *)sender
{
if (sender.state == UIGestureRecognizerStateBegan) {
NSLog(@"长按手势已经触发");
//一定要调用这个方法
[self becomeFirstResponder];
//创建菜单控制器
UIMenuController * menuvc = [UIMenuController sharedMenuController];
UIMenuItem * menuItem1 = [[UIMenuItem alloc]initWithTitle:@"复制" action:@selector(firstItemAction:)];
menuvc.menuItems = @[menuItem1];
[menuvc setTargetRect:CGRectMake(self.bounds.size.width/2, self.bounds.origin.y-5, 0, 0) inView:self];
[menuvc setMenuVisible:YES animated:YES];
}
}
#pragma mark--设置每一个item的点击事件
- (void)firstItemAction:(UIMenuItem *)item
{
//通过系统的粘贴板,记录下需要传递的数据
UIPasteboard *pboard = [UIPasteboard generalPasteboard];
pboard.string = self.text;
}
#pragma mark--必须实现的关键方法
//自己能否成为第一响应者
- (BOOL)canBecomeFirstResponder
{
return YES;
}
//能否处理Action事件
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(firstItemAction:)) {
return YES;
}
return [super canPerformAction:action withSender:sender];
}