I'm looking for a method called addNewItem:(NSToolbarItem *)item
or something like this that lets me add a programmatically created item to my toolbar, but I haven't found any. I would like to add an item that shows a popover when the user clicks on it, like in Safari when the user downloads something.

- 2,261
- 1
- 25
- 34
1 Answers
You need to have a class that conforms to the NSToolbarDelegate
protocol and have an instance of that class be the delegate of your toolbar. This delegate would, for example, implement -toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar:
, which returns an NSToolbarItem
instance for a given identifier, potentially creating that item on demand. By doing this, you’re preparing your delegate to return a toolbar item when the toolbar asks it for the item corresponding to an identifier.
Having done that, you can programatically add a new toolbar item to the toolbar by sending -[NSToolbar insertItemWithItemIdentifier:atIndex]
to the toolbar instance. The identifier string argument should match the one used in the paragraph above. If you need to remove an item, send -[NSToolbar removeItemAtIndex:]
to the toolbar.
This is described with examples in the Adding and Removing Toolbar Items section of the Toolbar Programming Topics for Cocoa document.
-
9why so complicated, Apple? – lukas Nov 15 '14 at 14:43
-
3@Lukas because back when NSToolbar was designed, techniques like this were necessary to reduce RAM consumption. This was a standard pattern and how _everything_ in Cocoa used to work. Only the new stuff doesn't work like this. – Abhi Beckert Sep 26 '15 at 06:21