转载

长按UITableViewCell弹出UIMenuController

在项目中想要添加一个长按Cell弹出UIMenuController的功能,当我在tableview中添加时是可以弹出来的,然而当在自定义cell.m文件中添加UILongPressGestureRecognizer时,可以触发事件,但是MenuController死活不出来,捣鼓了半天无果,只好google搜索,最后发现忘记实现下面的第三个方法。下面把解决方案记录一下。

长按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事件

[self addGestureRecognizer: [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longTap:)]];

2.处理长按事件

-(void)longTap:(UILongPressGestureRecognizer *)longRecognizer {  if (longRecognizer.state==UIGestureRecognizerStateBegan) {   [self becomeFirstResponder];   UIMenuController *menu=[UIMenuController sharedMenuController];   UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyItemClicked:)];   UIMenuItem *resendItem = [[UIMenuItem alloc] initWithTitle:@"转发" action:@selector(resendItemClicked:)];   [menu setMenuItems:[NSArray arrayWithObjects:copyItem,resendItem,nil]];   [menu setTargetRect:self.bounds inView:self];   [menu 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(resendItemClicked:)){   return YES;  }  return [super canPerformAction:action withSender:sender]; } #pragma mark  实现成为第一响应者方法 -(BOOL)canBecomeFirstResponder{  return YES; } 

4.处理item点击事件

#pragma mark method -(void)resendItemClicked:(id)sender{  NSLog(@"转发");  //通知代理 } -(void)copyItemClicked:(id)sender{  NSLog(@"复制");  // 通知代理  } 

喜欢我们的内容,关注官方微信公众账号:乐Coding。

正文到此结束
Loading...