cocoaappkitnspopupbuttonnstoolbar

Drop-down menu in NSToolbar like Mail.app


I'd like a toolbar button with an attached dropdown menu, like the "Flag" button in the toolbar in Mail.app:

Flag menu from Mail.app

I'd hoped that making a normal NSMenuItem and adding a menu as the menuFormRepresentation would do the trick, but that menu only appears when the button goes into overflow mode.

I had also hoped that adding an NSPopupButton as a custom view would work, but that makes the whole view a menu, whereas I want the left part of the component to behave like a normal button, and the right dropdown part bring up the menu.

Is there some trick to making the NSToolbarItem show a component like this, or is this two custom views stuck together?


Solution

  • There's nothing magical about NSToolbar here. That's just one of the ways you can set up NSSegmentedControl, regardless of whether it appears as a toolbar item's custom view or on its own.

    You can't set this up in Interface Builder (storyboard), but NSSegmentedControl has APIs for assigning menus to segments:

    segmentControl.setMenu(myMenu, forSegment: 1)
    segmentControl.setShowsMenuIndicator(true, forSegment: 1) // for the little arrow
    

    You probably want to set the tracking mode to momentary, since your segment control is acting as a set of visually-connected buttons, not a choose-one-of-N selector.

    When the user clicks either segment, your action method will need to use the selectedSegment to decide whether to perform the action associated with the "button" side or ignore the click (letting the menu show for the other side).