Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a UITabBar badge after the user clicks another tab?

I want to remove a badge as soon as the user clicks another tab. I am trying to do:

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    UITabBarItem *tbi = (UITabBarItem *)self.tabController.selectedViewController.tabBarItem;
    tbi.badgeValue = nil;
}

But it doesn't work.

like image 490
Sheehan Alam Avatar asked Aug 09 '10 23:08

Sheehan Alam


1 Answers

You want to remove a badge from the current tab, or the one touched?

The right place to do this, either way, is in your tab bar controller delegate, in:

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController;

Note that this function gets called whenever the user taps on a tab bar button, regardless of whether the new view controller shown is different from the old one, so you'll want to track your current visible view controller. This is where you'll update that, too:

- (void)tabBarController:(UITabBarController *)tabBarController 
        didSelectViewController:(UIViewController *)viewController {
    if(viewController != self.currentTabVC) {
        // if you want to remove the badge from the current tab
        self.currentTabVC.tabBarItem.badgeValue = nil;

        // or from the new tab
        viewController.tabBarItem.badgeValue = nil;

        // update our tab-tracking
        self.currentTabVC = viewController;
    }
}
like image 75
Seamus Campbell Avatar answered Sep 20 '22 23:09

Seamus Campbell