当用户长按分组 UITableView 中的单元格时,我正在尝试显示自定义 UIMenuController。但是,在成功检测到长按后,我似乎无法显示 UIMenuController。任何帮助是极大的赞赏。
MyViewController.h
@interface MyViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>
UITableView *table;
@property (nonatomic, retain) IBOutlet UITableView *table;
@end
在 cellForRowAtIndexPath 中,我附上了我的长按手势识别器
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SectionsTableIdentifier] autorelease];
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
[cell addGestureRecognizer:longPress];
[longPress release];
这是我的 handleLongPress 操作方法
-(void)handleLongPress:(UIGestureRecognizer *)longPress {
if (longPress.state == UIGestureRecognizerStateBegan) {
CGPoint pressLocation = [longPress locationInView:self.table];
NSIndexPath *pressedIndexPath = [self.table indexPathForRowAtPoint:pressLocation];
UIMenuItem *first = [[UIMenuItem alloc] initWithTitle:@"Save" action:@selector(saveRecent)];
UIMenuItem *second = [[UIMenuItem alloc] initWithTitle:@"Edit" action:@selector(editQuery)];
UIMenuController *menuController = [UIMenuController sharedMenuController];
menuController.menuItems = [NSArray arrayWithObjects:first,second,nil];
[menuController setTargetRect:longPress.view.frame inView:longPress.view.superview];
[menuController setMenuVisible:YES animated:YES];
[pressedIndexPath release];
}
}
Edit 和 Save 的 Action 方法只显示一个 UIAlertView。我还实现了以下方法,以确保在显示 UIMenuController 时仅显示保存和编辑选项
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender {
BOOL canPerform = NO;
if (action == @selector(saveRecent)) {
canPerform = YES;
}
if (action == @selector(editQuery)) {
canPerform = YES;
}
return canPerform;
}
我还声称 MyViewController 是第一响应者
-(BOOL)canBecomeFirstResponder {
return YES;
}