Thursday, March 7, 2013

Dynamic Menu Items in XCode 4 Interface Builder

I'm working on an OS X application, and I wanted to make a menu that dynamically changes one of the items when the user presses the ⌥ (alt) option key, like how Finder does in its "Go" menu.
Finder's Go menu showing the ⌥ dynamic menu item.
Searching the web pointed me to this article on developer.apple.com, and then to NSMenuItem where the details are described under -setAlternate:.

Here's how to make a dynamic menu item:

  1. Edit your menu in its .xib file in XCode's Interface Builder.
  2. Make two menu items, one after the other. The first is the normally visible one, and the second is the alternate choice.
  3. For the second menu item, edit the properties. Enable the "Alternate" checkbox, and then click in the "Key Equivalent" field and press the Option key.
Menu Item properties in Interface Builder
That's it. Hook the menu up in your code, setting the target for each item to call their corresponding selectors accordingly.  Read the guide to Menus on the Apple site to learn more.

When you run your application, and the menu appears, you will see the first menu item until you press the modifier key (option, for example).  The menu will swap the first menu item with the second.

No comments:

Post a Comment