項目中需要這個功能,網上找了下資料,有的說得不是很清楚,走了很多彎路才實現了,下面是實現步驟:
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