最近項(xiàng)目開發(fā)中遇到要復(fù)制Label上的文字的需求,經(jīng)過查閱資料整理開發(fā)。
下面是自己借鑒網(wǎng)上各位大神的方法實(shí)現(xiàn)自己的需求。
首先,創(chuàng)建自定義Label 集成UILabel
#import@interface LRCopyLabel : UILabel
@end
接著實(shí)現(xiàn)具體方法
@implementation LRCopyLabel
//拖拽
-(void)awakeFromNib {
[super awakeFromNib];
[self addLongPressGesture];
}
//手動(dòng)創(chuàng)建
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
[self addLongPressGesture];
}
return self;
}
//添加長(zhǎng)按手勢(shì)
- (void)addLongPressGesture {
self.userInteractionEnabled = YES;
UILongPressGestureRecognizer * longGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longAction:)];
[self addGestureRecognizer:longGesture];
}
//長(zhǎng)按觸發(fā)的事件
- (void)longAction:(UILongPressGestureRecognizer *)sender
{
if (sender.state == UIGestureRecognizerStateBegan) {
NSLog(@"長(zhǎng)按手勢(shì)已經(jīng)觸發(fā)");
//一定要調(diào)用這個(gè)方法
[self becomeFirstResponder];
//創(chuàng)建菜單控制器
UIMenuController * menuvc = [UIMenuController sharedMenuController];
UIMenuItem * menuItem1 = [[UIMenuItem alloc]initWithTitle:@"復(fù)制" 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--設(shè)置每一個(gè)item的點(diǎn)擊事件
- (void)firstItemAction:(UIMenuItem *)item
{
//通過系統(tǒng)的粘貼板,記錄下需要傳遞的數(shù)據(jù)
UIPasteboard *pboard = [UIPasteboard generalPasteboard];
pboard.string = self.text;
}
#pragma mark--必須實(shí)現(xiàn)的關(guān)鍵方法
//自己能否成為第一響應(yīng)者
- (BOOL)canBecomeFirstResponder
{
return YES;
}
//能否處理Action事件
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(firstItemAction:)) {
return YES;
}
return [super canPerformAction:action withSender:sender];
}