- 添加文件
CopyLabel ,继承自UILabel ,改写awakeFromNib 方法让其可以在storyboard 和xib 文件中也可以生效 - 更改为该类,即可长按复制
- 需要别的功能,添加
UIMenuItem 和相应的方法就好了
#import "CopyLabel.h"
@implementation CopyLabel
- (void)awakeFromNib{
[super awakeFromNib];
[self setUp];
}
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
[self setUp];
}
return self;
}
- (void)setUp{
self.userInteractionEnabled = YES;
[self addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(labelClick:)]];
}
- (void)labelClick:(UILongPressGestureRecognizer *)sender{
if(sender.state == UIGestureRecognizerStateBegan){
[self becomeFirstResponder];
UIMenuController * menu = [UIMenuController sharedMenuController];
[menu setTargetRect:CGRectMake(0,0,0,0) inView:self];
[menu setMenuVisible:YES animated:YES];
}
}
- (void)copy:(UIMenuController *)menu{
if (!self.text) return;
UIPasteboard * paste = [UIPasteboard generalPasteboard];
paste.string = self.text;
}
- (BOOL)canBecomeFirstResponder{
return YES;
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(copy:))
return YES;
return NO;
}
@end
|