How to programmatically add a new NSToolbarItem to an existing toolbar?

I am looking for a method called addNewItem:(NSToolbarItem *)item or something like this, which allows me to add a programmatically created item to my toolbar, but I did not find it. I would like to add an element that shows a popover when the user clicks on it, for example, in Safari, when the user loads something.

+6
source share
1 answer

You need to have a class that conforms to the NSToolbarDelegate protocol, and have an instance of this class that will be the delegate of your toolbar. This delegate, for example, would -toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar: which returns an NSToolbarItem instance for this identifier, potentially creating this item on demand. By doing this, you are preparing a delegate to return the toolbar item when the toolbar requests it for the item matching the identifier.

Having done this, you can programmatically add a new toolbar item to the toolbar by sending -[NSToolbar insertItemWithItemIdentifier:atIndex] to the toolbar instance. The identifier string argument must match the argument specified in the previous paragraph. If you need to remove an item, submit -[NSToolbar removeItemAtIndex:] to the toolbar.

This is described with examples in the Adding and Removing Toolbar Elements section of the Cocoa Toolbar Themes section.

+12
source

Source: https://habr.com/ru/post/896718/


All Articles