Introducing BarButtonBadge.h, the custom class to easily set a badge on a UIBarButtonItem. The usage is simple and understandable.
UIBarButtonItem *item = [BarButtonBadge barButtonWithImage:imagebadgeString:stringatRight:BOOLtoTarget:targetaction:action];
The class method accepts 5 mandatory parameters.
- 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.
- 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!"
- 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.
- id target - The class which will receive the message that your button was tapped
- SEL action - The selector message which will be sent to the target
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.