Wednesday, January 16, 2008

Selectable Toolbar Icons in RubyCocoa

So you'd like to have some nifty selectable toolbar items to make your preferences window really polished? Or maybe you'd like to use the toolbar as a tab-set like Coda does. No problem, here's how to do it.

Note: I'm using Leopard & Interface Builder 3. You can create selectable toolbars in Tiger, but the process is different and not within the scope of this article.

To start, in the window controller, add an ib_action:

ib_action :selectPrefPaneldo|sender|# We'll do stuff here later...
end

Then in Interface Builder, create the toolbar and the toolbar items. For each toolbar item:

  • Turn off the 'autovalidates' option
  • Set the action to target the selectPrefPanel: action on your window controller (probably the File's Owner)

Before you save the Nib, be sure and set the toolbar's delegate to the window controller.

Now back in the window controller code, implement a toolbarSelectableItemIdentifiers method in your controller:

deftoolbarSelectableItemIdentifiers(toolbar)@toolbaridents||=begin
    window.toolbar.toolbaritems.collect {|i| i.itemIdentifier }endend

Lastly, when the window loads, select the first toolbar item:

defawakeFromNib
  window.toolbar.selectedItemIdentifier = window.toolbar.toolbarItems[0].itemIdentifier
end

Viola! Now you have selectable toolbar items.

Here's the full source for the window controller.

It's worth mentioning that this isn't specific to RubyCocoa. You can do the same thing in Objective-C, Python, or Nu (example).

Next, I'll show you how to create the views that will go within your preferences window, and how to animate them to really finish it off.

Update: Find the next article here.

3 comments:

  1. Alternate Nu version of "toolbarSelectableItemIdentifiers method":http://pastie.textmate.org/140776 suggested by "Tim Burks":http://http://blog.neontology.com

    ReplyDelete
  2. Oh, thanks, thanks and thaks again. :D I'm currently building a ObjC/Cocoa app so I've been looking for this for a while.

    ReplyDelete
  3. Beautiful: I've been looking for something like this! Very easy to port to Objective-C!

    ReplyDelete