利用UIMenuController实现UITableViewCell点击的自定义菜单

以下是实现点击自定义UITableViewCell时展示一个自定义菜单实现回复、举报和复制文字的功能。

  • 1.在自定义UITableViewCell中实现以下方法:
-(BOOL)canBecomeFirstResponder
{
    return YES;
}
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    return action==@selector(replyAction:)||
    action==@selector(reportAction:)||
    action==@selector(copyAction:);
}
  • 2.实现三个自定义菜单项点击事件:
-(void)replyAction:(id)sender
{
    //走代理方法
}

-(void)reportAction:(id)sender
{
    //走代理方法
}

-(void)copyAction:(id)sender
{
    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    pboard.string = _comment.content;
    
}
  • 3.在自定义UITableViewCell中添加单击手势:
UITapGestureRecognizer *tapGesture = 
[[UITapGestureRecognizer alloc]initWithTarget:self 
action:@selector(showMenu)];
[self addGestureRecognizer:tapGesture];
  • 4.实现点击展示菜单方法:
-(void)showMenu
{
    if(self.isFirstResponder){
        [self resignFirstResponder];
        self.avatarBtn.userInteractionEnabled = YES;
    }else{
        [self becomeFirstResponder];
        self.avatarBtn.userInteractionEnabled = NO;
    }
    
    UIMenuItem *replyItem = [[UIMenuItem alloc]initWithTitle:@"回复" action:@selector(replyAction:)];
    UIMenuItem *reportItem = [[UIMenuItem alloc]initWithTitle:@"举报" action:@selector(reportAction:)];
    UIMenuItem *copyItem = [[UIMenuItem alloc]initWithTitle:@"复制" action:@selector(copyAction:)];
    UIMenuController *menuController = [UIMenuController sharedMenuController];
    menuController.menuItems = @[replyItem,reportItem,copyItem];
    [menuController setTargetRect:self.frame inView:self.superview];
    [menuController setMenuVisible:YES animated:YES];
}
  • 5.效果图


14556931660733.jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1、禁止手机睡眠[UIApplication sharedApplication].idleTimerDisabl...
    DingGa阅读 4,832评论 1 6
  • 概述在iOS开发中UITableView可以说是使用最广泛的控件,我们平时使用的软件中到处都可以看到它的影子,类似...
    liudhkk阅读 12,998评论 3 38
  • *7月8日上午 N:Block :跟一个函数块差不多,会对里面所有的内容的引用计数+1,想要解决就用__block...
    炙冰阅读 7,399评论 1 14
  • 夏季晴雨不走心,天蓝日暖绿蝉鸣。 忽变风云雨如倾,摇落暗香铺小径。 送你一地野菊花,绿叶铺毯便为家。 随意开落无人...
    梦碎了现实阅读 2,325评论 0 0
  • 注定会离别的人,还有必要再见吗? 还是不必了吧。 既然注定是过客, 又何必再见, 不如偏隅一方, 各自安好。 人这...
    流泪的叶子阅读 1,562评论 0 6

友情链接更多精彩内容