如何从AppDelegate.m设置tabBarItem的徽章(tabBarView不是root视图)
我可以通过以下代码更改AppDelegate.m中的徽章值:
UITabBarController *tabController = (UITabBarController *)self.window.rootViewController; [[tabController.viewControllers objectAtIndex:0] tabBarItem].badgeValue = @"Badge";
仅当tabBarViewController是窗口的根视图控制器时。
但是,在我的新程序中,tabBarController不是root视图。
我试过以下代码:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; UITabBarController *tabController = (UITabBarController *)[storyboard instantiateViewControllerWithIdentifier:@"tabBarController"] ; [[tabController.viewControllers objectAtIndex:0] tabBarItem].badgeValue = @"Badge";
它不会起作用。 tabBarItem不显示任何徽章。
编辑-
我添加了以下代码来检查tabController是否创建,答案是肯定的。
if (tabController) { NSLog(@"tabController has been created "); }else { NSLog(@"You have a null reference - The Object hasn't been created yet"); }
答案是肯定的。
2013-03-01 11:57:00.600报告[14854:907] tabController已创建
但是,预期的徽章仍然没有显示出来。
你可以尝试这个代码罗伯特先生
[[[[[self tabBarController] tabBar] items] objectAtIndex:0] setBadgeValue:[NSString stringWithFormat:@"%d", notificationCount ]];