长按UITableViewCell弹出UIMenuController

要实现长按弹出菜单栏需要做到以下三点:

1、在view(cell)或者viewController中调用-becomeFirstResponder方法;
2、你的view获得或者view controller需要实现 -canBecomeFirstResponder 方法,返回YES;
3、你的view获得或者view controller需要实现-canPerformAction:action withSender:sender 方法来隐藏或者现实响应的item;

cell中关键代码展示:

1.添加longpress事件

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
[self addGestureRecognizer: [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longTap:)]];
}
return self;
}

2.处理长按事件


#pragma mark - target
- (void)longTap:(UILongPressGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer state]==UIGestureRecognizerStateBegan)
    {
        
        [self becomeFirstResponder];
        
        //得到菜单栏
        UIMenuController *menuController = [UIMenuController sharedMenuController];
        UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyItemClicked:)];
        
        UIMenuItem *colloctionItem = [[UIMenuItem alloc] initWithTitle:@"收藏" action:@selector(collectionItemClicked:)];
        [menuController setMenuItems:[NSArray arrayWithObjects:copyItem,colloctionItem, nil]];
        //设置菜单栏位置
        [menuController setTargetRect:self.contentLabel.frame inView:self.contentLabel.superview];
        
        //显示菜单栏
        [menuController setMenuVisible:YES animated:YES];
    }
    
}

3.实现默认方法

#pragma mark 处理action事件

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

#pragma mark 实现成为第一响应者方法

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

4.处理item点击事件

#pragma mark method

- (void)copyItemClicked:(id)sender
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    [pasteboard setString:self.contentLabel.text];
}

-(void)collectionItemClicked:(id)sender{

}

在外层controller

#pragma mark scrollView delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([UIMenuController sharedMenuController].isMenuVisible) {//如果显示就隐藏
        [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
    }

}

你可能感兴趣的:(长按UITableViewCell弹出UIMenuController)