Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 752
Sheehan Alam Avatar asked Aug 07 '10 20:08

Sheehan Alam


4 Answers

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";
    }
}
like image 66
kharrison Avatar answered Nov 10 '22 00:11

kharrison


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

Also works.

like image 37
Sheehan Alam Avatar answered Nov 10 '22 00:11

Sheehan Alam


Swift version:

self.tabBarController?.selectedViewController?.tabBarItem.badgeValue="12";
like image 40
ManuelGomes Avatar answered Nov 10 '22 02:11

ManuelGomes


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"];
like image 1
Seamus Campbell Avatar answered Nov 10 '22 01:11

Seamus Campbell