Responding to Mac Menu Selections

It’s not too difficult to add menus and menu items to a Mac app using Xcode’s Object Library. What can be tricky is how to get your app to respond properly when someone chooses a menu item that you added.

Create an Action

There are two steps to handling a menu selection. The first step is to create an IBAction, which is a function that will get called when someone chooses the menu item. The following code shows an example of defining an IBAction for an Export menu item:

@IBAction func export(_ sender: NSMenuItem) {

}

Normally you write another function that does the actual work and call that function from the IBAction.

Connect the Menu Item to the Action

The second step is to connect the menu item to the action you created. Connecting the menu item is required to enable the menu item. If you find your menu items are disabled, make sure they’re connected.

Open the storyboard and make a connection (Control-drag) from the menu item to the First Responder item in the application scene. A HUD panel with a long list of actions will open. Select your action from the list. Now your app should be responding properly to menu selections.