UILabel+CopyLabelText

说明:这是一个带长按复制功能的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)