Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: How to get the selected UIMenuItem from UIMenuController

I am trying to use UIMenuCnotroller to show a list of dynamically generated items, they share the same action method, and so I need to know which item is selected in the single action method.

However, in the action method - (void)menuItemAction:(id)sender;the sender is actually the UIMenuController object, and I didn't find any method of UIMenuController can tell me which menuitem is selected.

One solution I can think of is to dynamically generate different action selectors for different items, and do some tricks in forwardInvocation

But is there any easier way?

like image 210
Hao Gong Avatar asked Jan 06 '12 10:01

Hao Gong


1 Answers

You can use UIMenuCnotroller like: 1) creation:

UIMenuController *menuController = [UIMenuController sharedMenuController];
        UIMenuItem *open = [[UIMenuItem alloc] initWithTitle:@"Open" action:@selector(open:)];
        UIMenuItem *reDownload = [[UIMenuItem alloc] initWithTitle:@"Re-Download" action:@selector(reDownload:)];

        [menuController setMenuItems:[NSArray arrayWithObjects:open, reDownload, nil]];
        [menuController setTargetRect:cell.frame inView:self.view];
        [menuController setMenuVisible:YES animated:YES];

        [open release];
        [reDownload release];

2) To catch actions should implement next methods:

- (BOOL) canPerformAction:(SEL)selector withSender:(id) sender 
{
    if (selector == @selector(open:))
    {
        return YES;
    }

    if (selector == @selector(reDownload:))
    {
        return YES;
    }

    return NO;
}

- (BOOL) canBecomeFirstResponder 
{
    return YES;
}

3) And realization of yours methods:

- (void) open:(id) sender 
{
    [self doSomething];
}

- (void) reDownload:(id) sender 
{
[self doSomething];
}

Hope, this helps.

like image 83
Igor Avatar answered Sep 19 '22 15:09

Igor