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 :selectPrefPanel do |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:
@toolbaridents ||= begin
window.toolbar.toolbaritems.collect {|i| i.itemIdentifier }
end
end
Lastly, when the window loads, select the first toolbar item:
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.

