DekGenius.com
[ Team LiB ] Previous Section Next Section

3.5 Menus

The NSMenu and NSMenuItem classes implement menus in Cocoa. NSMenu provides an implementation for actual menus, while NSMenuItem represents individual items within menus. An application's menus appear in the main menu bar across the top of the screen. By and large, an application's main menu is assembled in Interface Builder, which provides facilities for editing menu structures and setting menu item targets and actions. Additionally, Interface Builder has several pre-configured menus, such as File and Edit that contain standard menu items familiar to users. An application's main menu is contained in the main nib of an application.

Every application also has a Dock menu, which pops up when you right-click on an application's Dock icon. Dock menus are easily created in Interface Builder by connecting an instance of NSMenu to the File's Owner's dockMenu outlet. Alternatively, the application delegate can supply a Dock menu by implementing the method applicationDockMenu: (this is useful if you want to dynamically reconfigure the menu). A third way of specifying a Dock menu is to assemble the NSMenu object in a nib and specify the nib's file name in the application's Info.plist file under the AppleDockMenu key.

NSView objects manage contextual menus. In Interface Builder, every view has a menu outlet, which can be connected to an NSMenu object. The menu that you connect to this outlet will appear as a contextual menu when you right-click over the view. Contextual menus can be assigned to a view by overriding the method menuForEvent: in NSView subclasses. This method has an NSEvent object as the parameter and should be implemented to return an NSMenu. Because an event object is provided in this method, you can use it to return a menu based, for example, on the location of the event within the view. Example 3-5, in Section 3.9.1, shows how to extract this information from an NSEvent object.

    [ Team LiB ] Previous Section Next Section