Dynamic UIMenuItems with @selector and dynamic methods

后端 未结 2 1300
南方客
南方客 2020-12-29 12:15

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

相关标签:
2条回答
  • 2020-12-29 12:45

    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.

    0 讨论(0)
  • 2020-12-29 13:04

    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;
    }
    
    0 讨论(0)
提交回复
热议问题