Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top