Toolbars with HotCocoa

21 Jul 2009

I had the opportunity to add a toolbar to my
Silver Lining app the other day and though I’d
write down how I did it. This would, probably, have been easier if I had an
understanding of the Cocoa Toolbar.

The main thing that kept tripping me up is that you don’t add toolbar items
directly to the toolbar. Each item you want to add to the toolbar is given an
identifier (HotCocoa will generate one from the label if needed). Then, when you
create your toolbar, you specify which toolbar items are in the toolbar by
default and which items are available to be put in the bar.

Once the toolbar is created we don’t just append it to the window with the
normal << operator. We need to use toolbar= to assign the toolbar to the
window.

The toolbar we’re going to create is fairly simple. We want a button, with image, on the left for reloading and a search field on the right. We’ll put a flexible spacer in the middle to put them on opposite sides of the screen. (Note, there is currently a bug in HotCocoa where our specified items will be to the right and the spacer to the left. Things may not look correct until fixed.)

The first toolbar item we create is the reload button. We set the image on the
button to a file in the resources folder called reload.png. When the button is
clicked, we want to execute the reload_instances method.

The second item is the search box. You’ll notice we’re setting the :identifier
instead of the :label as we did for the reload button. The difference being,
the label will appear below the button and we don’t want Search appearing
below the search box. The reload button will have an identifier of Reload
created for it by HotCocoa.

With the search toolbar item in hand we create a search_field. The search
field is then assigned as the view in the search toolbar item using si.view=.

Finally, we create our toolbar. This is done with the toolbar method. We
want our default set of items to be the reload_item, :flexible_space and
search_item. We then assign the toolbar to our window with win.toolbar =
tb.

There are a few default toolbar items you can use, similar to
:flexible_space. They are: