3407707273_c05017779f 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.

silverlining_toolbar 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.)

reload_item = toolbar_item(:label => "Reload",
                           :image => image(:named => "reload"))
reload_item.on_action { reload_instances }

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.

search_item = toolbar_item(:identifier => "Search") do |si|
  search = search_field(:frame => [0, 0, 250, 30],
                        :layout => {:align => :right, :start => false})
  search.on_action { |sender| filter_instances(search) }

  si.view = search
end

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=.

@toolbar = toolbar(:default => [reload_item, :flexible_space, search_item]) do |tb|
  win.toolbar = tb
end

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:

  • :separator
  • :space
  • :flexible_space
  • :show_colors
  • :show_fonts
  • :customize
  • :print

That’s all folks. Have fun.