Getting NSMenuItem of NSMenu tree by title

≡放荡痞女 提交于 2019-12-06 12:04:33

问题


I have an NSMenu (let's say the Main Menu), with lots of NSMenus in it, and NSMenuItems at different levels.

I want to be able to get the NSMenuItem instance specifying the tree path (with the title of the corresponding NSMenus/NSMenuItems in it).

Example :

Menu :

  • File
    • New
    • Open
      • Document
      • Project
    • Save
    • Save As...

Path : /File/Open/Document

How would you go about it, in the most efficient and Cocoa-friendly way?


回答1:


I think that best way would be to obtain the NSMenuItem by specifying its title or, better, a custom defined tag.

#define kMenuFileNew 1
#define kMenuFileOpen 2

NSMenu *menu = [[NSMenu alloc] initWithTitle:@"File"];
NSMenuItem *item1 = [[NSMenuItem alloc] initWith..];
item1.tag = kMenuFileOpen;
[menu addItem:item1];


NSMenuItem* item2 = [menu itemWithTag:kMenuFileOpen];



回答2:


So, here it is; solved by creating a Category on NSMenu, and using recursion.

Code :

- (NSMenuItem*)getItemWithPath:(NSString *)path
{
    NSArray* parts = [path componentsSeparatedByString:@"/"];
    NSMenuItem* currentItem = [self itemWithTitle:[parts objectAtIndex:0]];

    if ([parts count]==1)
    {
        return currentItem;
    }
    else
    {
        NSString* newPath = @"";

        for (int i=1; i<[parts count]; i++)
        {
            newPath = [newPath stringByAppendingString:[parts objectAtIndex:i]];
        }

        return [[currentItem submenu] getItemWithPath:newPath];
    }
}

Usage :

NSMenuItem* i = [mainMenu getItemWithPath:@"View/Layout"]; 


来源:https://stackoverflow.com/questions/9852032/getting-nsmenuitem-of-nsmenu-tree-by-title

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!