如何在用户单击另一个选项卡后删除UITabBar徽章?

She*_*lam 10 iphone cocoa-touch objective-c uitabbarcontroller uitabbar

我想在用户点击其他标签后立即删除徽章.我想做:

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

    UITabBarItem *tbi = (UITabBarItem *)self.tabController.selectedViewController.tabBarItem;
    tbi.badgeValue = nil;
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

Sea*_*ell 12

您想要从当前标签中删除徽章,还是要触摸徽章?

无论哪种方式,执行此操作的正确位置都位于标签栏控制器委托中,位于:

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController;
Run Code Online (Sandbox Code Playgroud)

请注意,只要用户点击标签栏按钮,就会调用此函数,无论所显示的新视图控制器是否与旧视图控制器不同,因此您需要跟踪当前的可见视图控制器.这也是你要更新的地方:

- (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;
    }
}
Run Code Online (Sandbox Code Playgroud)