当前位置: 代码迷 >> 综合 >> How To Add Menus to the Menubar in Cocoa
  详细解决方案

How To Add Menus to the Menubar in Cocoa

热度:44   发布时间:2023-12-08 10:21:35.0

原文连接: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:

  1. 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:

  1. NSMenuItem  *testItem  =  [ [ [ NSMenuItem alloc ]initWithTitle : @ "Testing!" action : nilkeyEquivalent : @ "" ] autorelease ];
  2. NSMenu  *subMenu  =  [ [ [ NSMenu alloc ]initWithTitle : @ "Testing!" ] autorelease ];
  3. [testItem setSubmenu :subMenu ];
  4. [menubar addItem :testItem ];

If you want items in that menu, add them to the submenu:

  1. NSMenuItem  *testItem  =  [ [ [ NSMenuItem alloc ]initWithTitle : @ "Testing!" action : nilkeyEquivalent : @ "" ] autorelease ];
  2. NSMenu  *subMenu  =  [ [ [ NSMenu alloc ]initWithTitle : @ "Testing!" ] autorelease ];
  3. [subMenu addItemWithTitle : @ "Another test."action : nil keyEquivalent : @ "" ];
  4. [testItem setSubmenu :subMenu ];
  5. [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.

  1. if  ( [ [ NSUserDefaults standardUserDefaults ]boolForKey : @ "debugEnabled" ] )  {
  2. NSMenuItem  *debugItem  =  [ [ [ NSMenuItem alloc ]initWithTitle : @ "Debug" action : nil keyEquivalent : @ "" ]autorelease ];
  3. [debugItem setSubmenu :debugMenuFromNib ];
  4. [menubar addItem :debugItem ];
  5. }

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:

  1. NSMenu  *menubar  =  [ [NSApp delegate ]valueForKey : @ "menubar" ];

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:

  1. NSMenu  *menubar  =  [appController menubar ];

It’s not so hard. You can still get to it all in Cocoa with just a very little bit of preparation.