2
votes

I'm trying to display a custom UIMenuController when a User long presses on a cell in a grouped UITableView. However, I can't seem to get the UIMenuController to display after successfully detecting the long press. Any help is greatly appreciated.

MyViewController.h
@interface MyViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>
  UITableView *table;
  @property (nonatomic, retain) IBOutlet UITableView *table;
@end

In the cellForRowAtIndexPath I attach my Long Press Gesture Recognizer

cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SectionsTableIdentifier] autorelease];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    [cell addGestureRecognizer:longPress];
    [longPress release];

Here is my handleLongPress action method

-(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];
  }
}

The Action methods for the Edit and Save just display a UIAlertView. I also implemented the below method to ensure that when the UIMenuController is displayed only Save and Edit options will be present

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender {

 BOOL canPerform = NO;

 if (action == @selector(saveRecent)) {
    canPerform = YES;
 }
 if (action == @selector(editQuery)) {
    canPerform = YES;
 }

 return canPerform;
}

I'm also claiming MyViewController to be first responder

-(BOOL)canBecomeFirstResponder {

  return YES;
}
1

1 Answers

1
votes

I believe you need to have a view claiming firstResponder status in order to present the UIMenuController. I don't see that happening in your code.

I wrote up directions for using the UIMenuController as an answer to this question:

Customize UIMenuController