简体   繁体   中英

Set NSToolbarItem Unselected

I am currently trying to define an NSToolbar with selectable NSToolbarItems which represent tools in a drawing OSX application. I want the user to be able to select and deselect the tools(NSToolbarItems) to be used by clicking them .

If you happen to know Sketch, that is the toolbar behaviour I am looking for:

选定工具截图

In the image above you can see the "Edit" tool selected. If you click the item again, it gets deselected:

未选择的工具截图

I have been reading the Apple documentation for Toolbars and haven't found information about how to achieve this effect of being able to select / unselect toolbar items. In the "Selectable Toolbar Items" it says:

Your application can specify the currently selected toolbar item using the method setSelectedItemIdentifier: passing the identifier for the desired toolbar item. The currently selected toolbar item is returned by the method selectedItemIdentifier . If there is no currently selected, nil is returned.

but I haven't found where the setSelectedItemIdentifier: method is defined or if it even is what will solve my requirement.

What happens to my toolbar items now is that, once clicked, they can only be deselected by clicking another selectable item. Once an item is clicked, there will always be a selected item.

Is there any simple way of getting this solved? am I missing an important part of the documentation where it explains how to achieve this effect?

Thanks a lot!

ANSWER: So in the end it was as simple as setting the selectedItemIdentifier of the NSToolbar to nil . That causes the selected element to be deselected.

In order to unselect an NSToolbarItem , it is as simple as setting the selectedItemIdentifier of the NSToolbar object to nil .

I was initially confused by Apple documentation, in the Selectable Toolbar Items section, since it states that:

[...] The currently selected toolbar item is returned by the method selectedItemIdentifier . If there is no currently selected, nil is returned.

so I thought selectedItemIdentifier was simply a method that returned the currently selected toolbar item (no setting, just getting). But I believe that should be a typo. selectedItemIdentifier is get/set property, and in fact, setting it to nil unselects all the items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM