实现步骤:
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 = [self indexPathForRowAtPoint:location];
UIMyTableViewCell *cell = (UIMyTableViewCell *)recognizer.view;
//这里把cell做为第一响应(cell默认是无法成为responder,需要重写canBecomeFirstResponder方法)
[cell becomeFirstResponder];UIMenuItem *itCopy = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(handleCopyCell:)]; UIMenuItem *itDelete = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(handleDeleteCell:)]; UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems:[NSArray arrayWithObjects:itCopy, itDelete, nil]];
[menu setTargetRect:cell.frame inView:self];
[menu setMenuVisible:YES animated: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