How to add a badge to a UITabBar that is customizable?

Sheehan Alam picture Sheehan Alam · Aug 7, 2010 · Viewed 16.6k times · Source

I am adding a badge to my UITabBarController's UITabBar as such:

UITabBarItem *tbi = (UITabBarItem *)[stTabBarController.tabBar.items objectAtIndex:1];
tbi.badgeValue = @"2";

However, my UITabBarController is customizeable, so the index may change. How can I make sure the badge gets applied to the correct UITabBarItem?

Answer

kharrison picture kharrison · Aug 9, 2010

One suggestion you might consider is setting a tag on each tab bar item. You can do this in Interface Builder or when you create the item by code. You can then loop through the view controllers in the tab bar controller looking for the one with the tab bar item you are interested in. For example:

// #define MyTabBarItemTag 999

for (UIViewController *viewController in stTabBarController.viewControllers) {
    if (viewController.tabBarItem.tag == MyTabBarItemTag) {
        viewController.tabBarItem.badgeValue = @"2";
    }
}