美文网首页IOS收藏iOS 宝典iOS收藏
iOS 长按复制内容的Label (类似微信)

iOS 长按复制内容的Label (类似微信)

作者: Vincent20481 | 来源:发表于2016-10-21 14:40 被阅读1686次

先上效果图:

000000.gif

写一个继承UILabel 的EwenCopyLabel
.m代码

-(BOOL)canBecomeFirstResponder {
    
    return YES;
}

// 可以响应的方法
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(newFunc)) {
        return YES;
    }
    return NO;
}

//针对于响应方法的实现
-(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];
        
        [[NSNotificationCenter defaultCenter] addObserverForName:UIMenuControllerWillHideMenuNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
            self.backgroundColor = [UIColor whiteColor];
        }];
    }
    return self;
}

-(void)awakeFromNib {
    
    [super awakeFromNib];
    [self attachTapHandler];
}

-(void)handleTap:(UIGestureRecognizer*) recognizer {
  
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        NSLog(@"111");
        return;
    }else if (recognizer.state == UIGestureRecognizerStateBegan){
        NSLog(@"222");
        [self becomeFirstResponder];
        self.backgroundColor = UIColorRGB(236, 236, 236, 1.0);
        UIMenuItem * item = [[UIMenuItem alloc]initWithTitle:@"复制" action:@selector(newFunc)];
        [[UIMenuController sharedMenuController] setTargetRect:self.frame inView:self.superview];
        [UIMenuController sharedMenuController].menuItems = @[item];
        [UIMenuController sharedMenuController].menuVisible = YES;
    }
}

-(void)newFunc{
    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    pboard.string = self.text;
}

GitHub:快捷下载Demo https://github.com/GitHubazuo/LabelCopyDemo

相关文章

网友评论

  • 025c838455c0:当label在UItableViewCell上的时候确实会崩溃,这个已测
    Vincent20481:我这边的确没崩溃
  • 进击的程序猿儿:老哥,在cell上添加的话会crash啊。
    *** Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'child view controller:<UICompatibilityInputViewController: 0x7f94ab5c5320> should have parent view controller:<QM***ControllerViewController: 0x7f94aaed1b90> but requested parent is:<UIInputWindowController: 0x7f94a185c800>'
    weak啊:@因你而在_863d http://www.cocoachina.com/bbs/read.php?tid-1684754.html
    进击的程序猿儿:@Kevin20481 没试,项目要求在cell上。你可以试一试~
    Vincent20481:@因你而在_863d 在控制器崩不崩

本文标题:iOS 长按复制内容的Label (类似微信)

本文链接:https://www.haomeiwen.com/subject/yjqcuttx.html