Drop-down menu in NSToolbar like Mail.app
Asked Answered
P

1

6

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?

Pigfish answered 27/4, 2018 at 15:51 Comment(1)
Possible duplicate of How to implement a toolbar button with drop down menu?Bindle
P
10

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).

Pasahow answered 27/4, 2018 at 20:2 Comment(1)
NSToolbar does sometimes do magical things to embedded controls (e.g., NSSearchField renders differently in a toolbar than outside), so I was hoping that there was some way to trigger this magic for an NSButton. But your solution doesn't seem too onerous; a quick prototype is looking pretty good. Thanks!Pigfish

© 2022 - 2024 — McMap. All rights reserved.