Search code examples
objective-cuimenucontroller

UIMenuController: how to tell which menuItem is pressed?


I have a UILongPressGestureRecognizer on a UITableViewCell that displays a UIMenuController with some categories the user can pick from. These categories are stored in a NSMutableArray and can be customized by the user. I want to use one method to handle all category-presses in the UIMenuController. How can I pass the index of the selected UIMenuItem? Thanks in advance.

#pragma mark -
#pragma mark Custom Quick Menu Item

@interface QuickMenuItem : UIMenuItem 
{

}

@property (nonatomic, retain) NSIndexPath *indexPath;
@property (nonatomic, retain) NSMutableString *category;

@end

@implementation QuickMenuItem
@synthesize indexPath, category;

- (void)dealloc 
{
    [indexPath release];
    [category release];
    [super dealloc];
}

@end

#pragma mark -
#pragma mark Handle UILongPressGesture

- (void)handleLongItemPress:(UILongPressGestureRecognizer *)longPressRecognizer
{
    if (longPressRecognizer.state == UIGestureRecognizerStateBegan) 
    {
        NSIndexPath *pressedIndexPath = [queueTableView indexPathForRowAtPoint:[longPressRecognizer locationInView:queueTableView]];

        if (pressedIndexPath && (pressedIndexPath.row != NSNotFound) && (pressedIndexPath.section != NSNotFound)) 
        {
            [self becomeFirstResponder];
               UIMenuController *menuController = [UIMenuController sharedMenuController];
            NSMutableArray *categoryMenuItems = [NSMutableArray array];

            NSEnumerator *e = [self.stats.categories objectEnumerator]; // array with categories
            NSMutableString *cat;
            while (cat = [e nextObject]) 
            {
                QuickMenuItem *categoryMenuItem = [[QuickMenuItem alloc] initWithTitle:cat action:@selector(quickMenuCategoryPressed:)];
                categoryMenuItem.indexPath = pressedIndexPath;
                categoryMenuItem.category = cat;
                [categoryMenuItems addObject:categoryMenuItem];
                [categoryMenuItem release];
            }

            menuController.menuItems = [NSArray arrayWithArray:categoryMenuItems];
            [menuController setTargetRect:[queueTableView rectForRowAtIndexPath:pressedIndexPath] inView:queueTableView];
            [menuController setMenuVisible:YES animated:YES];
        }
    }
}

- (void)quickMenuCategoryPressed:(UIMenuController *)menuController
{
    QuickMenuItem *menuItem = [[[UIMenuController sharedMenuController] menuItems] objectAtIndex: ??]; // How to tell which category is selected?

    if (menuItem.indexPath) 
    {
        [self resignFirstResponder];

        // Perform action   
    }
}

Solution

  • You'll probably need to create some dynamic selectors, as described at Dynamic UIMenuItems with @selector and dynamic methods