原文连接:http://hopelessgeek.com/2006/11/22/how-to-add-menus-to-the-menubar-in-cocoa
It’s ridiculously simple. A lot of the solutions I’ve seen have people trying to get the menubar via Carbon calls and using hidden functions to convert the menu reference into a Cocoa object and then monkey with it this and that way, but, really, they’re missing the point of Cocoa if they’re doing this.
The menubar is just an NSMenu, folks.
Just add an item to your application delegate:
-
IBOutlet NSMenu *menubar
In Interface Builder, connect the two up and save. Done.
Inserting a New Menu
For a menu to be shown, it must have a submenu. For the sake of just getting a header in there, the following works:
-
NSMenuItem *testItem = [ [ [ NSMenuItem alloc ]initWithTitle : @ "Testing!" action : nilkeyEquivalent : @ "" ] autorelease ];
-
[testItem setSubmenu :subMenu ];
-
[menubar addItem :testItem ];
If you want items in that menu, add them to the submenu:
-
NSMenuItem *testItem = [ [ [ NSMenuItem alloc ]initWithTitle : @ "Testing!" action : nilkeyEquivalent : @ "" ] autorelease ];
-
[subMenu addItemWithTitle : @ "Another test."action : nil keyEquivalent : @ "" ];
-
[testItem setSubmenu :subMenu ];
-
[menubar addItem :testItem ];
You can also save a menu pre-made in your NIB and use the above concept to check for a default (say, “debugEnabled”) and then create a new item in the menu bar and attach that menu as a submenu to it.
-
NSMenuItem *debugItem = [ [ [ NSMenuItem alloc ]initWithTitle : @ "Debug" action : nil keyEquivalent : @ "" ]autorelease ];
-
[debugItem setSubmenu :debugMenuFromNib ];
-
[menubar addItem :debugItem ];
-
}
Outside of the Controller
Since you added it to the application delegate, you can get to it from outside that class rather easily with a little more preparation. Just add a KVC method to get (not set!) the menubar to the delegate class and then any other class can get to it as so:
If you have a link to your application delegate via some other means (I tend to import the class and then in my document init set an ivar to it with the proper class for typing purposes) then the following works as well:
It’s not so hard. You can still get to it all in Cocoa with just a very little bit of preparation.