實(shí)現(xiàn)步驟:
1.給cell添加UILongPressGestureRecognizer和相應(yīng)處理事件
(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做為第一響應(yīng)(cell默認(rèn)是無法成為responder,需要重寫canBecomeFirstResponder方法)
[cell becomeFirstResponder];UIMenuItem *itCopy = [[UIMenuItem alloc] initWithTitle:@"復(fù)制" 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{//復(fù)制cell
NSLog(@"handle copy cell");
}(void)handleDeleteCell:(id)sender{//刪除cell
NSLog(@"handle delete cell");
}
3.在自定義的cell里重寫canBecomeFirstResponder方法,返回yes
//為了讓菜單顯示,目標(biāo)視圖必須在responder鏈中,很多UIKit視圖默認(rèn)并無法成為一個(gè)responder,因此你需要使這些視圖重載 canBecomeFirstResponder方法,并返回YES
- (BOOL)canBecomeFirstResponder{
return YES;
}
經(jīng)過這幾步,就可以成功顯示了,又在網(wǎng)上看到一篇講這個(gè)的外文,分享一下:
http://www.intridea.com/blog/2010/12/22/developers-notes-for-uimenucontroller