Thursday, January 6, 2011

Badges on UIBarButtonItems

Badges in iOS are the de-facto way to communicate new/unread information to users.  The SDK allows for setting badges on tab bar items and on the main .app bundle icon.  But what if you want to set a badge on a toolbar item?  There is no official way to make a badge on a toolbar item, even though you as a developer may want to incorporate a badge.

Introducing BarButtonBadge.h, the custom class to easily set a badge on a UIBarButtonItem.  The usage is simple and understandable.

UIBarButtonItem *item = [BarButtonBadge barButtonWithImage:image
                              badgeString:string
                           atRight:BOOL
                           toTarget:target
                     action:action];

The class method accepts 5 mandatory parameters.

  1. UIImage *buttonImage -  The one limitation of the class is that it only produces barButtonItems that contain an icon/picture.  Due to the unpredictable width of a barButtonItem with text, the class does not support a barItem that has a title.  So, use a picture instead.  The barItem will render at 30x30 so a square image is best.
  2. NSString *badgeString - The text you want displayed inside the badge icon.  Can be as simple as @"1" or as elaborate as @"Unread News! Touch here!"
  3. BOOL atRightSideOfScreen - If the barItem is destined to be on the right hand side of the screen, set to YES and the badge icon will be displayed on the left side of the barItem.  Otherwise, it might not be visible on the screen.
  4. id target - The class which will receive the message that your button was tapped
  5. SEL action - The selector message which will be sent to the target
The class returns an autoreleased UIBarButtonItem, so please retain it immediately.

This class comes bundled with another class that is not authored by me, called CustomBadge.  CustomBadge does all the heavy lifting with rendering badges on screen, and is very effective.  The license for CustomBadge is included inside the file.  I have no claims to CustomBadge and do not offer it as my own creation.  BarButtonBadge extends functionality of CustomBadge only.  For this reason, both  classes must be copied into your project in order to work correctly.

You can download a sample project here which contains the necessary custom classes.

No comments:

Post a Comment