Search code examples
cocoansmenuitemnsmenu

How can I get a NSMenuItem from a submenu?


I have a reference to the outermost menu, but I'm trying to get a reference to an NSMenuItem that's nested in a submenu:

NSMenuItem* file_menu = [menu itemWithTitle:@"File];

file_menu is obviously a submenu (NSMenu), but I'm not sure how to get an item out of it's itemarray. I've tried casting it to an NSMenu and performing itemWithTitle as a selector with no luck.

How can I get the first NSMenuItem out of it?


Solution

  • Like this.

    NSMenuItem* file_menu = [menu itemWithTitle:@"File"];
    if (file_menu.hasSubmenu) {
        NSArray *menu_items = file_menu.submenu.itemArray;
        NSMenuItem *first_item = [menu_items objectAtIndex:0];
    }
    

    If the menu item has a sub menu the submenu property will let you access it, you can then access its menu items using the itemArray property.