在开发过程中,一个需求就是需要label中的文本是可复制的,在网上搜集资料,最后封装如下:
(1)首先创建一个类继承于UI Label,我将它命名为LYLabel;因为label默认是不接收事件的,我们需要自己 在LYLabel.m文件中给label添加touch事件。代码如下:
-(void)addTouch{
self.userInteractionEnabled = YES; //用户交互的总开关
UILongPressGestureRecognizer *touch = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(addgesture:)];
[self addGestureRecognizer:touch];
}
(2)手势触发的事件:
-(void)addgesture:(UILongPressGestureRecognizer*) recognizer{
[self becomeFirstResponder];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setTargetRect:self.frame inView:self.superview];
[menu setMenuVisible:YES animated:YES];
}
(3)再开启一下其他必要的功能,如开启第一响应者等:
// default is NO
- (BOOL)canBecomeFirstResponder{
return YES;
}
//"反馈"关心的功能
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
return (action == @selector(copy:));
}
//针对于copy的实现
-(void)copy:(id)sender{
UIPasteboard *pboard = [UIPasteboard generalPasteboard];
pboard.string = self.text;
}
(4)最后,绑定事件,主要看你的label实在Xib或者Storyboard画的还是用代码创建的:
如果用代码创建的话:
//绑定事件
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self addTouch];
}
return self;
}
如果再xib或者storyboard文件中画的话:
-(void)awakeFromNib{
[super awakeFromNib];
[self addTouch];
}
(5)调用。封装完成之后,调用就很简单了:
LYCopyLabel *lable = [[LYCopyLabel alloc]initWithFrame:CGRectMake(0, 100, 200, 100)];
lable.text = @"sajdlajkjdka";
[self.view addSubview:lable];
最后,一个可复制文本的lable就完成了。功能简单,闲来无事,写了一个demo。