Cocoa: Add a Search Bar and Other Controls to Titlebar

When you’re building apps for OS X, you have an option to create a Unified Titlebar + Toolbar using Interface builder, and add UI Controls to this toolbar, like in the screenshot below.

Unified Toolbar

While this works and looks great, you might want to minimize UI chrome, and present Controls in the titlebar itself – which seems to be the trend in many recent apps (including Sparrow, the mail client, and the Mac App Store to quote a few).

Titlebar Search

This kind of UI can be achieved by using a custom NSWindow class called INAppStoreWindow (download here).

To begin, change the class of the Window in your XIB from NSWindow to INAppStoreWindow using the Identity Inspector. The Titlebar can now be customized to include toolbar controls.

Customizing the Titlebar – Programmatically:

This is pretty straightforward, and can be done in the awakeFromNib method of your AppDelegate/View Controller.

// Create a pointer to the Window instance

YourAppDelegate *delegate = (YourAppDelegate *)[[NSApplicationsharedApplication] delegate];

INAppStoreWindow *aWindow = (INAppStoreWindow*)[delegate window];

// Set titlebar height

aWindow.titleBarHeight = 45.0;

// Customize the Titlebar’s View

NSView *titleBarView = aWindow.titleBarView;

// Create and add a Search Field into the Titlebar

NSSize buttonSize = NSMakeSize(180.f, 60.f);

NSRect buttonFrame = NSMakeRect((titleBarView.bounds.size.width – (buttonSize.width + 10)), NSMidY(titleBarView.bounds) – (buttonSize.height / 2.f), buttonSize.width, buttonSize.height);

NSSearchField *searchField= [[NSSearchField alloc]initWithFrame:buttonFrame];

searchField.autoresizingMask = NSViewMinXMargin;

[titleBarView addSubview:searchField];

Customizing the Titlebar – Using Interface Builder:

Add a new Custom View into your XIB, and make it an Outlet in the Delegate / View Controller

Custom Toolbar IB

Set the size of this View the same as the required Titlebar view (for best results), and add the required controls into this View (like the Search Bar in the above screenshot).

Also ensure that autoResizing is set :

View autoresizing

You’ll need to do just a little bit of customization in awakeFromNib:

// Create a pointer to the Window instance

ARVAppDelegate *delegate = (ARVAppDelegate *)[[NSApplication sharedApplication] delegate];

INAppStoreWindow *aWindow = (INAppStoreWindow*)[selfwindow];

// Set titlebar height

aWindow.titleBarHeight = 45.0;

// Add the custom View as a SubView of the titleBar


That should do it. Your Window should now look like this:

Titlebar with SearchField

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>