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

16,817

Solution 1

UITabBarItem *tbi = (UITabBarItem *)self.tabController.selectedViewController.tabBarItem;
tbi.badgeValue = @"New";

Also works.

Solution 2

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";
    }
}

Solution 3

Swift version:

self.tabBarController?.selectedViewController?.tabBarItem.badgeValue="12";

Solution 4

I'd use an NSMutableDictionary property on the class that owns the tab bar controller, associating tab names with positions, and a method to retrieve by name:

-(UITabBarItem*)getTabByName:(NSString*)tabName {
    return [stTabBarController.tabBar.items objectAtIndex:[[tabDict valueForKey:tabName] intValue]];
}

Initialize the dictionary in your setup code for each tab, since you know the tab index at that time:

[tabDict setValue:[stTabBarController.tabBar.items objectAtIndex:1] forKey:@"myTabName"];
Share:
16,817
Sheehan Alam
Author by

Sheehan Alam

iOS, Android and Mac Developer. i can divide by zero.

Updated on June 17, 2022

Comments

  • Sheehan Alam
    Sheehan Alam almost 2 years

    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?