Creating NSMenu with NSMenuItems in it, programmat

2019-03-15 02:47发布

问题:

First, I'd like to point out that this question is probably already asked, I just couldn't find any answers from them.

So, I'm programmatically trying to create a NSMenu and NSMenuItem to the main bar, so fe. NSMenu would be File and then it would have 3x NSMenuItem in it, New, Open and Save.

But nothing's working, here's what I have currently:

NSMenu *fileMenu = [[NSMenu alloc] initWithTitle:@"File"];
NSMenuItem *newMenu = [[NSMenuItem alloc] initWithTitle:@"New" action:NULL keyEquivalent:@""];
NSMenuItem *openMenu = [[NSMenuItem alloc] initWithTitle:@"Open" action:NULL keyEquivalent:@""];
NSMenuItem *saveMenu = [[NSMenuItem alloc] initWithTitle:@"Save" action:NULL keyEquivalent:@""];
[newMenu setMenu:fileMenu];
[openMenu setMenu:fileMenu];
[saveMenu setMenu:fileMenu];

But nothing happens, I'm pretty sure I have to tell the application that it should use fileMenu, but how do I do that, and if that's not the problem, then what is? I'm pretty new at this stuff, but interested in learning, so just any tip will be better than nothing!

回答1:

When you set the menu, you set the menu that appears for that item, not its parent menu.

To add those three items to your menu, use:

[fileMenu addItem: newMenu];
[fileMenu addItem: openMenu];
[fileMenu addItem: saveMenu];

And then to add the menu to the menu bar:

NSMenuItem *fileMenuItem = [[NSMenuItem alloc] initWithTitle: @"File"];
[fileMenuItem setSubmenu: fileMenu]; // was setMenu:
[[NSApp mainMenu] addItem: fileMenuItem];
[fileMenuItem release];

Every menu owns multiple menu items; a single menu item can be responsible for a submenu; and all these menus are anchored to the UI by [NSApp mainMenu].