Searching NSMenuItem inside NSMenu recursively

淺唱寂寞╮ 提交于 2019-12-02 07:51:00

问题


The method itemWithTitle locates a menu item within a NSMenu. However it looks only inside the first level. I cannot find a ready-to-use method that will do the same job recursively by searching inside all the nested submenus. Or, somehow equivalently, a function that swipes NSmenu's recursively.

It looks quite incredible to me that such a thing would not exist. Maybe there is some function not directly related to NSMenu that can come in handy?


回答1:


Ok, since I really need to do this clumsy workaround for a number of specific reasons (beyond the scope of this post, and quite uninteresting anyway) I ended up coding it myself.

Here is the snippet:

NSMenuItem * mitem;

while (mitem) { // loop over all menu items contained in any submenu, subsubmenu, etc.

     // do something with mitem ....

     mitem = next_menu_item(mitem);
}

which is powered by the functions:

NSMenuItem * goto_submenu(NSMenuItem * mitem){

    NSMenu * submen = [mitem submenu];
    if (submen && [[submen title] isNotEqualTo:@""] && [submen numberOfItems])
        return goto_submenu([submen itemAtIndex:0]);

    return mitem;
};

NSMenuItem * next_menu_item(NSMenuItem * mitem){

    NSMenu * menu = [mitem menu];

    if ([menu indexOfItem:mitem]==([menu numberOfItems]-1)) //if is last item in submenu go to parent item
        return [mitem parentItem];

    return goto_submenu([menu itemAtIndex:([menu indexOfItem:mitem]+1)]);
};


来源:https://stackoverflow.com/questions/26044110/searching-nsmenuitem-inside-nsmenu-recursively

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