苹果在iOS8之后,UILabel这个控件不在给我们提供好长按进行复制的操作,接下来我们自己写一个关于复制Lable上面的文字;
创建一个label继承UILabel;
代码如下:
-(BOOL)canBecomeFirstResponder { return YES; } // 可以响应的方法 -(BOOL)canPerformAction:(SEL)action withSender:(id)sender { return (action == @selector(copy:)); } //针对于响应方法的实现 -(void)copy:(id)sender { UIPasteboard *pboard = [UIPasteboard generalPasteboard]; pboard.string = self.text; } //UILabel默认是不接收事件的,我们需要自己添加touch事件 -(void)attachTapHandler { self.userInteractionEnabled = YES; UILongPressGestureRecognizer *touch = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; [self addGestureRecognizer:touch]; } //绑定事件 - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self attachTapHandler]; } return self; } -(void)awakeFromNib { [super awakeFromNib]; [self attachTapHandler]; } -(void)handleTap:(UIGestureRecognizer*) recognizer { [self becomeFirstResponder]; UIMenuItem *copyLink = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copy:)]; [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObjects:copyLink, nil]]; [[UIMenuController sharedMenuController] setTargetRect:self.frame inView:self.superview]; [[UIMenuController sharedMenuController] setMenuVisible:YES animated: YES]; }
这样就可以实现了.
下面这段代码是改变Label上面的文字颜色
NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:@"我:是"]; NSRange redRange = NSMakeRange(0, [[noteStr string] rangeOfString:@":"].location); [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:redRange]; [label setAttributedText:noteStr] ;