TweetFollow Us on Twitter

Creating Interface Builder Palettes with Bindings Support

Volume Number: 21 (2005)
Issue Number: 10
Column Tag: Programming

Creating Interface Builder Palettes with Bindings Support

Palettizing Your Custom NSView Subclasses to Take Advantage of Cocoa Bindings

by Jeff LaMarche


The introduction of Cocoa Bindings back in 10.3 (Panther) was a very well-received addition to the arsenal of the Cocoa developer, and many of us have begun to use them in our applications despite the loss of some backward compatibility. Bindings enable us to build applications much faster than we can without them, and result in much more easily maintained software.

Although Cocoa has an incredible assortment of controls and views for us developers to use when crafting an application, pretty much every serious Cocoa developer has, at one time or another, had to create custom views. Sometimes we write custom views of very limited applicability, but sometimes we create ones that are useful outside of the application they were written for. For the latter kind, we have the option of creating Interface Builder Palettes out of them, allowing the view to be easily added to any application's nib file.

Unfortunately, the process of creating a palette, as documented, does not create a palette with support for bindings. If you open Interface Builder and select an existing palettized view that you've created, then press ?4 you'll see that the only bindings available to you are the default NSView bindings of hidden and tooltip. The same is true if you drag a "Custom" view item from the Containers palette and change its class to your NSView subclass. At first glance, there does not seem to be an easy way to take advantage of bindings in your custom views.

This month, we're going to walk through the process of creating an Interface Builder palette that has usable bindings. We're going to create a fairly simple view which draws a gradient. This view will have two attributes--a start color and a finish color--and we'll create bindings for both of them. The completed project for this month can be downloaded from the MacTech FTP site.


Fire up Xcode and select ??N to create a new project, or select New Project... from the File menu. When the new project assistant window comes up scroll down until you see the category for Standard Apple Plug-ins, and select IBPalette (figure 1). Name your project MTGradientView. Although it is generally okay to have spaces in Xcode project names, when using this particular template to create a new view (as opposed to palettizing an existing view), you should give the project the same name as the view you plan to create, since the project template is set up to expect that.

Figure 1. Selecting the IBPalette project template in Xcode.

When the project is open, take a look at it. There's something you should take note of here: there are two targets to this project, and neither one creates an executable. Since an Interface Builder palette is designed to be used in multiple applications, the code that makes up the view or views contained in the palettes get put into a framework and installed in your local Frameworks directory (~/Library/Frameworks). The additional code and resources that Interface Builder needs, such as the code and nibs that create the inspector and palette, go into an Interface Builder palette that gets installed automatically in your local Palettes directory (~/Library/Palettes). Once you successfully compile a palette project, the palette will become available for your use the next time you launch Interface Builder.

It's important to understand the way the project is laid out for a couple of reasons. First of all, if you use the palettized view in an application, any user of your application must have the framework installed on their machine, or the view will not work. You can handle this in two ways. Either you can use an installer to install the framework on the user's machine at the same time that you install the application. The other much more user-friendly and Mac-like way is to embed the framework right into your application. We'll take a look at how to do that at the end of the article.

The second reason why it's important to understand the architecture of an IBPalette project occurs when you want to palettize an existing NSView subclass you've previously written. In that case, it becomes important to add the class to the correct project target; if you add the NSView subclass to the palette project instead of the framework project, your plug-in will not work.

Creating a Gradient

Before we code the view, let's create a category on NSColor that will make it easier to draw a gradient. The code for this category must be included in the framework project. There is no file template for creating categories, so you can either import the category from the article's project available on MacTech's FTP site, or use another file template, such as the Objective-C Class or the Empty File in Project template.


//The header file for our category.

#import <Cocoa/Cocoa.h>
@interface NSColor(interpolate) 
+(NSColor *) colorByInterpolatingColor: (NSColor *)color1
   withColor: (NSColor *)color2
   basedOnProgress: (int)progress
   outOfPossibleSteps: (int)steps;

As you see, we're adding a class method to NSColor. This method will create an autoreleased color based on two existing colors. It will weight the interpolation of the colors based on the last two parameters. If it's a 10-pixel wide gradient view, and we want the color for the third pixel, we would pass 3 for the first parameter and 10 for the second, creating a color that is a 30% blend of one color and 70% of the other. The implementation of the method involves a simple mathematical interpolation of each of the component of the color and the creation of a new NSColor instance based on that interpolation.


@implementation NSColor(interpolate)
+(NSColor *) colorByInterpolatingColor: (NSColor *)color1
   withColor: (NSColor *)color2
   basedOnProgress: (int)progress
   outOfPossibleSteps: (int)steps
   float red1 = [color1 redComponent];
   float green1 = [color1 greenComponent];
   float blue1 = [color1 blueComponent];
   float alpha1 = [color1 alphaComponent];
   float red2 = [color2 redComponent];
   float green2 = [color2 greenComponent];
   float blue2 = [color2 blueComponent];
   float alpha2 = [color2 alphaComponent];
   float newRed = red2 + ((float)progress / (float)steps) * 
      (red1 - red2);
   float newGreen = green2 + ((float)progress / 
      (float)steps) * (green1 - green2);
   float newBlue = blue2 + ((float)progress / (float)steps) 
      * (blue1 - blue2);
   float newAlpha = alpha2 + ((float)progress / 
      (float)steps) * (alpha1 - alpha2);

   return [NSColor colorWithCalibratedRed:newRed 
      green:newGreen blue:newBlue alpha:newAlpha];

It's not really important that you understand what's going on in this category in order to understand how to palettize a view, but this is a handy category to have around.

Creating the Custom View

The project template created an empty subclass of NSView for us already based on the project name. We know that we need two NSColor instance views, so let's add those to MTGradientView.h, along with declarations for the mutators and accessors. Creating mutators and accessors whose names conform to the Key-Value Coding (KVC) naming standard is the vitally important first step in adding binding support to your view. Fortunately, the KVC naming standard is exactly the same as the Objective-C instance variable naming convention.


#import <Cocoa/Cocoa.h>

@interface MTGradientView : NSView
   NSColor *leftColor;
   NSColor *rightColor;
- (NSColor *)leftColor;
- (void)setLeftColor:(NSColor *)newLeftColor;
- (NSColor *)rightColor;
- (void)setRightColor:(NSColor *)newRightColor;

Let's also add the implementations of our accessors to MTGradientView.m. You'll notice that in both mutators, we've placed a call to [self setNeedsDisplay:YES] because we know that changing either color of the gradient necessarily changes the appearance of the view:

//Accessors & Mutators to add to MTGradientView.m

- (NSColor *)leftColor
   return leftColor;
- (void)setLeftColor:(NSColor *)newLeftColor
   [newLeftColor retain];
   [leftColor release];
   leftColor = newLeftColor;
   [self setNeedsDisplay:YES];
- (NSColor *)rightColor
   return rightColor;
- (void)setRightColor:(NSColor *)newRightColor
   [newRightColor retain];
   [rightColor release];
   rightColor = newRightColor;
   [self setNeedsDisplay:YES];

Now, let's implement the view's drawRect: method.

//drawRect: in MTGradientView.m

- (void)drawRect:(NSRect)rect 
   int i;
   NSRect b = [self bounds];
   int steps = b.size.width;
   for (i = 0; i <steps; i++)
      NSColor *curColor = [NSColor colorByInterpolatingColor:
         [self rightColor] withColor:[self leftColor]
         basedOnProgress:i outOfPossibleSteps:steps];
      NSBezierPath *path = [NSBezierPath bezierPath];
      [curColor setStroke];
      [path moveToPoint:NSMakePoint(i,0)];
      [path lineToPoint:NSMakePoint(i,b.size.height)];
      [path setLineWidth:1.0];
      [path stroke];

That draws the gradient, so... we're done with our view, right?

Nope. In order to create a palette, the view must also implement initWithCoder: and encodeWithCoder: so that it can be serialized into the nib file. Let's replace the stub implementations of initWithCoder: and encodeWithCoder: with real ones. Interface Builder is capable of creating nibs using either an NSArchiver or an NSKeyedArchiver, so we'll add support for both methods of archiving, even though the use of NSArchiver has been deprecated:

//Serialization methods for MTGradientView.m

- (id)initWithCoder:(NSCoder *)coder
   self = [super initWithCoder:coder];
   if (self)
      if ([coder allowsKeyedCoding])
         [self setLeftColor:[coder 
         [self setRightColor:[coder 
         [self setLeftColor:[coder decodeObject]];
         [self setRightColor:[coder decodeObject]]; 
   return self;
- (void)encodeWithCoder:(NSCoder *)coder
   [super encodeWithCoder:coder];
   if ([coder allowsKeyedCoding])
      [coder encodeObject:[self leftColor] 
      [coder encodeObject:[self rightColor] 
      [coder encodeObject:[self leftColor]];
      [coder encodeObject:[self rightColor]];

Adding Bindings

We've already done most of the work needed to support bindings in our view, which was to create KVC-compliant mutators and accessors. There's one other step we need to take in order to let Interface Builder know what bindings our view supports: We have to "expose" the bindings. This is done by overriding NSObject's initialize method, which gets called before any objects are initialized. In that method, we have to call another of our class' class methods named exposeBinding: for each binding that we want to expose.

//initialize method in MTGradientView.m

+ (void)initialize
   [self exposeBinding:@"leftColor"];
   [self exposeBinding:@"rightColor"];

Clean Up

The last thing we have to do to our view before we can create a palette out of it, is to release our two instance variables by overriding dealloc.

//dealloc method in MTGradientView.m

- (void)dealloc
   [leftColor release];
   [rightColor release];
   [super dealloc];

Create the Palette

Now that we have a serializable view, we need to create a palette for it. The palette is a panel that will get added to the Interface Builder palettes (figure 2). Expand the Palette folder, then inside that expand the Classes folder and single-click on MTGradientViewPalette.h. We need to add an IBOutlet instance variable so that we can access our view from the palette.


#import <InterfaceBuilder/InterfaceBuilder.h>
#import "MTGradientView.h"

@interface MTGradientViewPalette : IBPalette
   IBOutlet MTGradientView *view;

@interface MTGradientView (MTGradientViewPaletteInspector)
- (NSString *)inspectorClassName;

Next expand the Resources folder, double-click on MTGradientViewPalette.m and wait for Interface Builder to open up.

Figure 2. Interface Builder's palettes. Here, the built-in Controls palette is currently selected.

Once Interface Builder is open and ready to go, drag MTGradientView.h over from XCode to MTGradientViewPalette.nib's main window and then drag MTGradientViewPalette.h over as well. This will let Interface Builder know about the changes we've made to these two header files. Double-click the icon called Palette Window to open up the window (if it's not already open). This "window" will not actually appear as a window, but rather its content pane will become part of the Interface Builder palette.

Now switch to the Containers palette (figure 3) and drag a custom view (the lower left item) over to the palette's window. You can make it any size you want, but since it's the only view we're going to have in our palette, you might as well have it take up most of the space.

Figure 3. The Containers palette.

Now single-click the custom view you just added and press ?5 to bring up the view's custom class inspector. Change the selected class from NSView to MTGradientView.

Figure 4. The completed palette window.

Single-click on the File's Owner icon and change the selected class for the file's owner to MTGradientViewPalette. Control-drag from the File's Owner icon to the MTGradientView in the palette window and connect it to the view outlet we created earlier. Save and go back to Xcode. You can leave Interface Builder open if you want; we'll be back in a few minutes.

In Xcode, single-click on MTGradientViewPalette.m. We have an opportunity, by overriding the method finishInstantiate, to initialize the parameters of our NSView. This will allow us to dictate how the view will appear when drawn in Interface Builder. Let's set our view to draw a gradient from red to blue when displayed in Interface Builder. The project template created a stub implementation of the finishInstantiate method; go ahead and add the code in bold to the existing stub.

//finishInstantiate in MTGradientViewPalette.m

- (void)finishInstantiate
   [view setLeftColor:[NSColor blueColor]];
   [view setRightColor:[NSColor redColor]];

An Inspector

At this point, we could use our palette, provided that we wanted to only use bindings. But we really should add an inspector to allow the user to change the two color attributes. The attribute inspector is the floating window that appears when you type ?1 in Interface Builder where you can set initial values for the currently selected control or item. We'll create an inspector using the other class and nib file created for us. Single-click on MTGradientViewInspector.h and let's add IBOutlet methods for the two color wells our inspector will need.


#import <InterfaceBuilder/InterfaceBuilder.h>

@interface MTGradientViewInspector : IBInspector
   IBOutlet NSColorWell *rightColor;
   IBOutlet NSColorWell *leftColor;

Double-click on MTGradientViewInspector.nib, which should open up in Interface Builder. Before we proceed, drag MTGradientViewInspector.h from Xcode over to the newly-opened nib window to tell Interface Builder about our new outlets. Single-click on the File's Owner icon, and press ?5 to bring up the custom class inspector. Change the File's Owner's class to MTGradientViewInspector.

Next, add two color wells from the Controls palette to the inspector window. You should also add labels to tell the user which is the left and which is the right.

Figure 5. The completed inspector window.

Now, we need to connect the two color wells we just added to our inspector's class' NSColorWell outlets. We can do this by control-dragging from the File's Owner icon to each of the color wells, connecting them to the appropriate outlet. Also control-drag from the File's Owner icon to the Inspector Window icon, and connect it to the window outlet. Save and this time, quit right out of Interface builder before going back to Xcode.

Back in Xcode, single-click on MTGradient ViewInspector.m. In this class, there are two methods that we need to implement; the project template has already given us stub implementations of both of them. In the ok: method, we need to take the values from our inspector and put them into the view. In our case, that means we need to take the colors from the two color wells and provide those values to our gradient view. In the revert: method, we have to take the attributes from the view and put them back into the controls. In our case, that means taking the colors from the view and setting the color wells based on them. Doing this is relatively straightforward code, once you know that you can get a reference to the view being edited by calling [self object]. You can leave the init method alone; it is fine just the way the template created it.


- (void)ok:(id)sender
   MTGradientView *selView = [self object];
   [selView setLeftColor:[leftColor color]];
   [selView setRightColor:[rightColor color]];
   [super ok:sender];
- (void)revert:(id)sender
   MTGradientView *selView = [self object];
   [leftColor setColor:[selView leftColor]];
   [rightColor setColor:[selView rightColor]];
   [super revert:sender];

Guess what? Our palette is now functional. Go ahead and compile using the MTGradientView or All target, then open up Interface Builder. In the list of palettes, there should be a new one called MTGradientView. Select it, and voila! There it is. Isnt' it purty?

Figure 6. The completed palette in action inside Interface Builder.

You can drag MTGradientViews from the palette onto application windows exactly like you do with the built-in palettes. You can set the view's initial color values in the attributes inspector and you can bind both leftColor and rightColor just as you would the bindings of any of the delivered controls. Pretty cool, huh?

Figure 7. The gradient view's bindings.

The only real problem with using this view is that the code for producing the view is external to your application contained in a framework in your home directory. That means that your application will not work on other machines unless you install that framework on their machine.

Making the Framework Embeddable

The solution to this problem is relatively simple: Make the framework embeddable. Go back to Xcode and expand the Targets group in the Groups & Files pane. You should see three targets: one for the MTGradientView, one for the MTGradient ViewFramework, and one called All. Single-click on the MTGradientViewFramework target, then right-click (or control-click if you're old-school and using a one-button mouse) and select Duplicate from the contextual menu. This will create a new target called MTGradientViewFramework Copy; rename it to MTGradientViewFramework Embed.

Because Interface Builder needs access to the framework, we have to keep the original target so that the framework gets built and installed to the local frameworks directory where Interface Builder has access to it. But we also want to build an embeddable version that doesn't get installed. Single-click the new target if it's not already selected, and press ?I to bring up the target inspector. Click on the Build tab and select deployment on the Collections popup menu.

One of the options under the deployment collection is Skip Install. Click the checkbox next to it so that it becomes checked. This will stop this target from installing the framework created by this target. Next, we need to change the value of the Installation Directory to a special value that will allow it to be embedded. Change it to read @executable_path/../Frameworks (see Figure 8).

Figure 8. The deployment setting for the embedded framework target.

Drag the new target over onto the All target, which will cause your new target to get built when someone builds all targets. Now, if you compile with either the new target or the All target and look in the project's build folder, you will see a new folder called UninstalledProducts. Inside that folder is the embeddable version of your framework.

Embedding the Framework

You can now create applications that include the MTGradientView functionality right inside the executable, which means no annoying framework installation for your users. Let's take a look at how you go about doing this, as it involves a bit more than simply including the framework in your application project. Create a new project in Xcode using the Cocoa Application project template, and call it MTGradientViewTester. Once the project is open, right-click on the Frameworks group and select Add?Existing Frameworks...

When the standard open sheet comes up, navigate to the UninstalledProducts folder of the palette project's build folder and select the MTGradientViewFramework.framework file. Now, expand the Targets group and expand the MTGradientViewTester target. You'll see three build phases in there. We need to add a fourth. Select the MTGradientViewTester Target and select New Build Phase?New Copy Files Build Phase from the Project menu. Single-click the new build phase that you just added and press ?I to bring up its inspector.

On the inspector for the build phase, you'll see a pop-up menu called Destination. Change the value of that pop-up to read Frameworks, which tells this phase to copy its contents to the Frameworks directory of the application bundle. Now drag the MTGradientViewFramework.framework from the Frameworks group to this new copy phase. If the drag worked, the name of the copy phase should change from Copy Files to Copy Files (1).

The End

That's it. The framework is now embedded and you can build deployable applications using the gradient view we just palettized! And best of all, every time you build your application, it will embed the most current version of the MTGradient ViewFramework. Go ahead and try adding an MTGradientView to this application's nib file. Try binding it to variables, and binding NSColorWells to the same variables. I'm not going to walk you through building the tester application, as it's pretty straightforward, but in the article's source code available from the MacTech FTP site, I've included a complete tester app that shows how to use bindings with the custom view we created. The tester application allows you to change the gradient by changing the left and right color with color wells.

Jeff LaMarche wrote his first line of code in Applesoft Basic on a Bell & Howell Apple //e in 1980 and he's owned at least one Apple computer at all times since. Though he currently makes his living consulting in the Mac-unfriendly world of "Enterprise" software, his Macs remain his first and greatest computer love. You can reach him at


Community Search:
MacTech Search:

Software Updates via MacUpdate

Between 2 Taps - Tap for Tap interview M...
Hello, and welcome back to Between 2 Taps, Tap for Tap’s Indie Dev interview series. [Read more] | Read more »
Facility 47 (Games)
Facility 47 1.0.1 Device: iOS Universal Category: Games Price: $3.99, Version: 1.0.1 (iTunes) Description: You wake up alone and freezing in an icy cell. You try the cell door but it’s locked, it seems that you are stuck with no... | Read more »
The best Photoshop alternative on iPad
Instagram and Lightroom are great and all, but sometimes people need to get extra creative with their image editing.Like, Photoshop creative. If you're one of these people, take a look at our pick for the best mobile Photoshop experience on iPad... | Read more »
The Walking Dead: No Man’s Land guide -...
A new update for The Walking Dead: No Man’s Land was released last week, making it the perfect time for you to head back to your base and take out some walkers. Here’s the lowdown on what’s new to the game, and how to take advantage. [Read more] | Read more »
Goat Rider guide - Tips and tricks to st...
We've all been there. One second, we're riding high on a crazed goat, and the next, we've been tossed off it like someone who's no good at goat ridin'. [Read more] | Read more »
Real Boxing 2 CREED: How to become a gre...
Just in time for Rocky fans who can’t wait to see CREED, the latest movie, we have the official tie-in game,Real Boxing 2 CREED. It builds on the success of its predecessor and there’s lots to take in so we at 148apps thought we’d run you through... | Read more »
CoinOp Heroes 2 guide - How to build an...
CoinOp Heroes 2 justlaunched and, like all clickers, it's dangerously addictive stuff. You have to furiously tap your screen to defeat wave after wave of foes and earn an insane amount of cash to spend on character upgrades and an army of minions... | Read more »
Dr. Panda Firefighters (Education)
Dr. Panda Firefighters 1.0.1 Device: iOS Universal Category: Education Price: $2.99, Version: 1.0.1 (iTunes) Description: FIGHT FIRES AND SAVE THE DAY!Work together with Dr. Panda and his firefighting team to rescue his trapped... | Read more »
Puddle + (Games)
Puddle + 1.0 Device: iOS iPhone Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: Puddle is back in a new "+" edition featuring enhanced graphics, new videos and Apple TV support ! No IAP and No Ads. Dive into Puddle... | Read more »
Football Manager Mobile 2016 (Games)
Football Manager Mobile 2016 7.0.0 Device: iOS Universal Category: Games Price: $8.99, Version: 7.0.0 (iTunes) Description: Football Manager Mobile 2016 is designed to be played on the move and is the quickest way to manage your... | Read more »

Price Scanner via

Adorama Black Friday deals: Up to $400 off Ma...
Adorama has released their Black Friday deals for 2015. Save up to $400 on MacBook Pros, $200 on MacBooks and MacBook Airs, and $270 on iMacs. Use code RYBFDEAL during checkout to see these prices.... Read more
B&H Photo Deals: $200 off 12-inch 1.2GHz...
In addition to the B&H Photo Black Friday week sales we posted yesterday, B&H has lowered their price on two products to $200 off MSRP: - 12″ 1.2GHz Gray Retina MacBook: $1399 save $200 - 13... Read more
Best Buy Early Access: Today only, Up to $125...
Best Buy has iPad Air 2s on sale for up to $125 off MSRP and Apple Watch models on sale on their online store for up to $100 off MSRP with special codes through midnight CT tonight. Choose free... Read more
UPPERCASE DESIGNS Premium Ultra Thin Keyboard...
UPPERCASE Designs today announced its new Premium Ultra Thin Keyboard Protector and its Palm Rest Protector Set for the 12-inch MacBook. The accessories provide durable protection for the 12-inch... Read more
Al Jazeera Launches New iOS And Android Mobil...
Doha, Qatar based Al Jazeera has launched new mobile and tablet apps on the iOS and Android systems bringing the latest Al Jazeera news and programmes live together with on-demand personalisation.... Read more
B&H Photo Holiday Sale: Up to $250 off Ma...
B&H Photo has all new Macs on sale for up to $500 off MSRP as part of their Holiday sale including free shipping plus NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $1799 $200 off - 15″ 2.... Read more
Free Aura ‘Ultimate’ Mac App For Gmail Update...
Miami, Florida based Crosscoded has announced Aura 1.2.0, an update to the Mac app for Gmail. Aura mixes the power of a native client with the flexibility of the Gmail web app with support for up to... Read more
Apple Will Edge Closer to Samsung in Smartpho...
Total smartphone shipments for 2015 are projected to decline by 9.7% to 1.286 billion units, according to the latest report from global market research firm TrendForce. Though Chinese vendors have... Read more
Sidefari – Split Screen Multitasking In Safar...
Francisco Cantu’s Sidefari is a simple web browser designed to act as a companion to Safari on the iPad. With multitasking in iOS 9, Sidefari uses the new Safari View Controller to show an extra... Read more
12-inch MacBooks in stock for up to $120 off,...
Adorama has 12″ Retina MacBooks in stock for up to $120 off MSRP including free shipping plus NY & NJ sales tax only. For a limited time, Adorama will include a free Apple USB-C to USB Adapter,... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Merchant Operations Manager: *Apple* Pay -...
Changing the world is all in a day's work at Apple . If you love innovation, here's your chance to make a career of it. You'll work hard. But the job comes with more than Read more
*Apple* Pay QA Manager - Apple Inc. (United...
Changing the world is all in a day's work at Apple . If you love innovation, here's your chance to make a career of it. You'll work hard. But the job comes with more than Read more
Sr Software Engineer *Apple* Pay - Apple In...
Changing the world is all in a day's work at Apple . If you love innovation, here's your chance to make a career of it. You'll work hard. But the job comes with more than Read more
Hardware Systems Architect - *Apple* Watch...
# Hardware Systems Architect - Apple Watch Job Number: 38449977 Santa Clara Valley, Califo ia, United States Posted: Apr. 16, 2015 Weekly Hours: **Job Summary** The Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.