美文网首页
UILable 长按复制

UILable 长按复制

作者: 小雨雨儿 | 来源:发表于2016-09-07 16:19 被阅读7次

    1.添加长按的手势

    UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(showMenuAction:)];
    [self.lable setUserInteractionEnabled:YES];
    [self.lable addGestureRecognizer:longGesture];
    

    2.实现方法

    - (BOOL)canBecomeFirstResponder{
        return YES;
    }
    
    - (BOOL)canPerformAction:(SEL)selector withSender:(id) sender {
        if (selector == @selector(copy:)) {
            return YES;
        }
        return NO;
    }
    
    - (void)copy:(id)sender {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        [pasteboard setString:self.lable.text];
    }
    
    - (void)showMenuAction:(UILongPressGestureRecognizer *)sender {
        if (sender.state == UIGestureRecognizerStateBegan) {
            
            [self becomeFirstResponder];
            
            CGPoint location = [sender locationInView:[sender view]];
            
            UIMenuController *menuController = [UIMenuController sharedMenuController];
            [menuController setTargetRect:CGRectMake(location.x, location.y, 0.0f, 0.0f) inView:sender.view];
            
            [menuController setMenuVisible:YES animated:YES];
        }
    }
    
    

    相关文章

      网友评论

          本文标题:UILable 长按复制

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