views:

112

answers:

4

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?

A: 

Keep a reference to the tab bar item that you want to modify.

EDIT as a response to your code request:
I believe that there is a single place in your app where you update the badges on the tab bar items. Just add an array of tab bar items (or separate tab bar items) as a member(s) of that class (+ properties if needed) and update the items directly without fetching from the current tab bar items list ((UITabBarItem *)[stTabBarController.tabBar.items objectAtIndex:1];).

For instance, if you decide to keep references to the tab bar items directly (without an array) then the code might look like that:

// Put the next code right after initiating the tab bar and/or after adding new tab bar items to it...

self.newsTabBarItem = (UITabBarItem *)[stTabBarController.tabBar.items objectAtIndex:1];
self.friendsTabBarItem = (UITabBarItem *)[stTabBarController.tabBar.items objectAtIndex:2];

// etc.
Michael Kessler
Can you show me in code?
Sheehan Alam
I have edited my answer. See if it helps you.
Michael Kessler
A: 

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"];
Seamus Campbell
A: 
UITabBarItem *tbi = (UITabBarItem *)self.tabController.selectedViewController.tabBarItem;
tbi.badgeValue = @"New";

Also works.

Sheehan Alam
A: 

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