项目中需要这个功能,网上找了下资料,有的说得不是很清楚,走了很多弯路才实现了,下面是实现步骤:
1.给cell添加UILongPressGestureRecognizer和相应处理事件
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{..............
UILongPressGestureRecognizer * longPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:selfaction:@selector(cellLongPress:)];
[cell addGestureRecognizer:longPressGesture];
return cell;
}
2.配置和显示UIMenuController
- (void)cellLongPress:(UIGestureRecognizer *)recognizer{
if (recognizer.state ==UIGestureRecognizerStateBegan) {
CGPoint location = [recognizer locationInView:self];
NSIndexPath * indexPath = [selfindexPathForRowAtPoint:location];
UIMyTableViewCell *cell = (UIMyTableViewCell *)recognizer.view;
//这里把cell做为第一响应(cell默认是无法成为responder,需要重写canBecomeFirstResponder方法)
[cell becomeFirstResponder];
UIMenuItem *itCopy = [[UIMenuItemalloc] initWithTitle:@"复制"action:@selector(handleCopyCell:)];
UIMenuItem *itDelete = [[UIMenuItemalloc] initWithTitle:@"删除"action:@selector(handleDeleteCell:)];
UIMenuController *menu = [UIMenuControllersharedMenuController];
[menu setMenuItems:[NSArray arrayWithObjects:itCopy, itDelete, nil]];
[menusetTargetRect:cell.frame inView:self];
[menu setMenuVisible:YESanimated:YES];
[itCopy release];
[itDelete release];
}
}
- (void)handleCopyCell:(id)sender{//复制cell
NSLog(@"handle copy cell");
}
- (void)handleDeleteCell:(id)sender{//删除cell
NSLog(@"handle delete cell");
}
3.在自定义的cell里重写canBecomeFirstResponder方法,返回yes
//为了让菜单显示,目标视图必须在responder链中,很多UIKit视图默认并无法成为一个responder,因此你需要使这些视图重载 canBecomeFirstResponder方法,并返回YES
- (BOOL)canBecomeFirstResponder{
return YES;
}
经过这几步,就可以成功显示了,又在网上看到一篇讲这个的外文,分享一下:
http://www.intridea.com/blog/2010/12/22/developers-notes-for-uimenucontroller