在项目中想要添加一个长按Cell弹出UIMenuController的功能,当我在
tableview中添加时是可以弹出来的,然而当在自定义cell.m文件中添加UILongPressGestureRecognizer时,可以触发事件,但是MenuController死活不出来,捣鼓了半天无果,只好google搜索,最后发现忘记实现下面的第三个方法。下面把解决方案记录一下。
要实现长按弹出菜单栏需要做到以下三点:
1.在view(cell)或者viewController中调用-becomeFirstResponder方法;
2.你的view或者viewcontroller需要实现 -canBecomeFirstResponder 方法,返回YES;
3.你的view或者viewcontroller需要实现-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:selfaction:@selector(longTap:)]];
}
return self;
}
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:)){
returnYES;
}else if (action==@selector(resendItemClicked:)){
returnYES;
}
return[super canPerformAction:action withSender:sender];
}
#pragma mark实现成为第一响应者方法
-(BOOL)canBecomeFirstResponder{
returnYES;
}
4.处理item点击事件
#pragma mark method
-(void)resendItemClicked:(id)sender{
NSLog(@"转发");
//通知代理
}
//复制到系统粘贴板
-(void)copyItemClicked:(id)sender{
NSLog(@"复制");
UIPasteboard*pasteBoard = [UIPasteboard generalPasteboard];
NSArray* array = [self.text componentsSeparatedByString:@":"];
pasteBoard.string= [array lastObject];
}
网友评论