I am trying to use UIMenuController for a dynamical menu (titles and actions come from a server). The problem is that I have to use UIMenuItems initWithTitle:action: where a
Unless the menu items do the same thing, why should they share an action? I would go ahead and write actions that specify a behavior you want and link the menu items up to those.
That approach would work, although you need a unique selector-name for every button and a mapping from that name to whatever you want to target.
For the selector name a unique string has to be chosen (UUIDs or maybe a sanitized & prefixed version of the title would work). Then you need one method that resolves the call and "alias" it with the different selector names:
- (void)updateMenu:(NSArray *)menuEntries {
Class cls = [self class];
SEL fwd = @selector(forwarder:);
for (MenuEntry *entry in menuEntries) {
SEL sel = [self uniqueActionSelector];
// assuming keys not being retained, otherwise use NSValue:
[self.actionDict addObject:entry.url forKey:sel];
class_addMethod(cls, sel, [cls instanceMethodForSelector:fwd], "v@:@");
// now add menu item with sel as the action
}
}
Now the forwarder can look up what URL is associated with the menu item:
- (void)forwarder:(UIMenuController *)mc {
NSLog(@"URL for item is: %@", [actionDict objectForKey:_cmd]);
}
To generate the selectors you could use something like:
- (SEL)uniqueActionSelector {
NSString *unique = ...; // the unique part
NSString *selString = [NSString stringWithFormat:@"menu_%@:", unique];
SEL sel = sel_registerName([selString UTF8String]);
return sel;
}