M@'s Musings

« Back to blog
 

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:

def toolbarSelectableItemIdentifiers(toolbar)
  @toolbaridents ||= begin
    window.toolbar.toolbaritems.collect {|i| i.itemIdentifier }
  end
end

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

def awakeFromNib
  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.

Posted
Filed under:
3 Comments
Jan 18, 2008
M@ McCray said...
Alternate Nu version of "toolbarSelectableItemIdentifiers method":http://pastie.textmate.org/140776 suggested by "Tim Burks":http://http://blog.neontology.com
Feb 24, 2008
Guillom said...
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.
Mar 13, 2008
Mike said...
Beautiful: I've been looking for something like this! Very easy to port to Objective-C!

Leave a comment...

Theme by Cory Watilo.
More great Posterous themes at themes.posterous.com.