相关文章推荐
爱搭讪的开水瓶  ·  Android 停止 ...·  2 年前    · 
奔放的蜡烛  ·  VBA: ...·  2 年前    · 
纯真的芒果  ·  Resolve errors and ...·  3 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

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.

@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, 2015 at 6:21

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question . Provide details and share your research!

But avoid …

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers .