UILabel长按复制
mLabel.m
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.userInteractionEnabled = YES;
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressCellHandle:)];
[self addGestureRecognizer:longPressGesture];
}
return self;
}
-(void)longPressCellHandle:(UILongPressGestureRecognizer *)gesture
{
[self becomeFirstResponder];
UIMenuController *menuController = [UIMenuController sharedMenuController];
UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(menuCopyBtnPressed:)];
menuController.menuItems = @[copyItem];
[menuController setTargetRect:gesture.view.frame inView:gesture.view.superview];
[menuController setMenuVisible:YES animated:YES];
[UIMenuController sharedMenuController].menuItems=nil;
}
-(void)menuCopyBtnPressed:(UIMenuItem *)menuItem
{
[UIPasteboard generalPasteboard].string = self.text;
}
-(BOOL)canBecomeFirstResponder
{
return YES;
}
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(menuCopyBtnPressed:)) {
return YES;
}
return NO;
}
ViewController.m
#import "ViewController.h"
#import "mLabel.h"
- (void)viewDidLoad {
[super viewDidLoad];
MLabel *label = [[MLabel alloc] initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, 50)];
label.textAlignment = NSTextAlignmentCenter;
label.text = @"长按这里可以复制这里的文字";
label.textColor = [UIColor grayColor];
label.backgroundColor = [UIColor yellowColor];
[self.view addSubview:label];
}
就酱...