UITableViewCell中添加复制逻辑


@interface ICUserInfoCell(){
    UIMenuItem * _copyMenuItem;
}
@end

@implementation ICUserInfoCell
- (id)initWithStyle:(UITableViewCellStyle)cell reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:cell reuseIdentifier:reuseIdentifier];
    if (self) {
        [self layoutSubview];
        
        UILongPressGestureRecognizer * longPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
        [self addGestureRecognizer:longPressGesture];

    }
    return self;
}

- (void)copyComment:(UIMenuController *)menu {
    UIPasteboard *pasteboard  = [UIPasteboard generalPasteboard];
    pasteboard.string = self.detailLabel.text;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(copyComment:)) {
        return YES;
    }
    return  [super canPerformAction:action withSender:sender];
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}
- (void)longPress:(UILongPressGestureRecognizer *)longRecognizer
{
    if (longRecognizer.state == UIGestureRecognizerStateBegan) {
        [self becomeFirstResponder];
        [[UIMenuController sharedMenuController] update];
        if (!_copyMenuItem) {
            _copyMenuItem   = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyComment:)];
        }
        [[UIMenuController sharedMenuController] setMenuItems:@[_copyMenuItem]];
        [[UIMenuController sharedMenuController] setTargetRect:self.frame inView:self.superview];
        [[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
    }
}

你可能感兴趣的:(UITableViewCell中添加复制逻辑)