IOS: how to get selected UIMenuItem from UIMenuController

I am trying to use UIMenuCnotroller to display a list of dynamically generated elements, they use the same action method, 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 a UIMenuController object, and I have not found any UIMenuController method that can tell me which menu item is selected.

One solution I can think of is to dynamically create different action selectors for different elements and perform some tricks in forwardInvocation

But is there an easier way?

+6
source share
3 answers

Ok, I solved it. This is due to the launch of [NSObject forwardInvocation:] and a bit dirty, but the resulting code is pretty minimal. The answer is here: fooobar.com/questions/905298 / ...

+1
source

You can use UIMenuCnotroller as: 1) creating:

 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) In order to catch actions, the following methods should be implemented:

 - (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 the implementation of your methods:

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

Hope this helps.

+2
source

The easiest way is to use a different @selector method for each menu @selector

<strong> Examples:

 UIMenuItem *oneObj = [[UIMenuItem alloc] initWithTitle:@"One" action:@selector(One:)]; UIMenuItem *twoObj = [[UIMenuItem alloc] initWithTitle:@"Two" action:@selector(Two:)]; 
+1
source

Source: https://habr.com/ru/post/905297/


All Articles