开发者

Trouble Displaying UIMenuController When Cell Tapped In UITableView

开发者 https://www.devze.com 2023-01-26 19:12 出处:网络
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

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 cellForRowAtIn开发者_StackOverflowdexPath 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;
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号