mattmccray

 
« Nuapp | Home | Animating NSViews In … »

Selectable Toolbar Icons in RubyCocoa

» Published January 16, 2008 under Cocoa, Software

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.


3 comments

01.18.08 @ 17:03 M@ McCray said...
Alternate Nu version of toolbarSelectableItemIdentifiers method suggested by Tim Burks http://blog.neontology.com
02.24.08 @ 06:37 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.
03.13.08 @ 16:03 Mike said...
Beautiful: I’ve been looking for something like this! Very easy to port to Objective-C!

No trackbacks

Trackback link:

Please enable javascript to generate a trackback url


You may use Textile, or simple html tags (B,I). Feel free to use Emoticons too. Oh, and please limit yourself to only five links per comment. Anything more and you'll probably get detained by the spam police.