Badged UIBarButtonItem

A new project (nearly ready to release; stay tuned) required some custom UI. One element was a badged UIBarButtonItem, for which I wrote a custom class, which I am releasing as open source here:

So what’s the use case? You have a UIBarButtonItem in a navigation bar that you want to adorn with a badge, much like you might adorn an app icon or tab on a tab bar with a badge. Sadly, UIBarButtonItem does not support badging. But it does support using a custom view for the button’s UI.

The class FFBadgedBarButtonItem builds a custom view that contains a UIImageView and a label. A tap gesture recognizer is added to the containing view.

My particular need required a custom image for the button, so I defined the following default initializer:

-(id)initWithImage:(UIImage *)image target:(id)target action:(SEL)action;

The target and action are just passed along as arguments for the tap gesture recognizer.

You need to make sure your image is sized well for use in a UIBarButtonItem. Then it is offset in the containing view to allow for the badge label to appear over the top right corner when needed.

The badge label uses some layer trickery to present a round badge by specifying a cornerRadius equal to half the height of the label. (The label’s width and height are equal, turning a square into a circle.) A red background completes the effect.

Best of all, this is no harder to use than a standard UIBarButtonItem in your code. For example:

UIImage *image = /* ... */
self.navigationItem.leftBarButtonItem = 
    [[FFBadgedBarButtonItem alloc] initWithImage:image 

And updating the badge is as simple as assigning an NSString:

FFBadgedBarButtonItem *button = 
    (FFBadgedBarButtonItem *)self.navigationItem.leftBarButtonItem;
button.badge = @"3";

Remove the badge by assigning nil to the badge property.

A sample project with the source code for the class is available on Github. The class should also be available via CocoaPods “real soon” under the name FFBadgedBarButtonItem.

Admittedly, since this class was created for a specific project, there are some elements of that project’s requirements baked into this implementation, like badge position, size, color, and font. These things are easily made more customizable, of course, and I welcome your pull requests!

Posted in: iDevBlogADay

Comments are closed.

Read previous post:
Caching +imageForURL: Results

About a month ago I wrote about the recurring but ever-solvable problem of loading images in the background without losing...