2016-07-27 27 views
-1

使用目标c开发iOS应用程序。在我的应用程序中,如果用户没有注册,那么注册视图控制器是rootViewController。如果用户是注册,那么tabBarController有三个选项卡是rootViewController。我必须从任何视图控制器设置tabBarItem徽章值。假设如果我在第三个选项卡上并且它正在与另一个视图控制器一起继续,并且我在该视图控制器上,则必须从此处更改第一个视图控制器的徽章值tabBarItem。在我的情况下tabBarItem徽章值更新只有我去该标签,我在viewWillAppear中使用iOS tabBarItem徽章值从任何视图更改

NSString *upcomingcount=[NSString stringWithFormat:@"%lu",(unsigned long)self.arrbadge.count]; 
      self.navigationController.tabBarItem.badgeValue=upcomingcount; 

有没有什么办法可以从任何ViewController中设置badgeValue?我想更新任何徽章值ViewController

回答

1

PLZ使用此方法在应用程序委托

- (void)update_badgeWithViewControllerIndex:(NSInteger)ViewControllerIndex { 


      UITabBarController *tabBarController =(UITabBarController*)[[(AppDelegate*) 
                     [[UIApplication sharedApplication]delegate] window] rootViewController]; 


       // Set the tab bar number badge. 
       UITabBarItem *tab_bar = [[tabBarController.viewControllers objectAtIndex:ViewControllerIndex] tabBarItem]; 

       // Show the badge if the count is 
       // greater than 0 otherwise hide it. 

       if ([badgeValue > 0) { 
        [tab_bar setBadgeValue:badgeValue]; // set your badge value 
       } 

       else { 
        [tab_bar setBadgeValue:nil]; 
       } 



    } 

使用这种方法 在每一个的viewController创建

@property (nonatomic,strong) AppDelegate *appDelegate; 




self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 

    [self.appDelegate update_badgeWithViewControllerIndex:yourViewControllerIndex]; 
+0

不工作!只有当我们继续使用视图控制器时,仍然会更新徽章。感谢您的回复 – goks

+0

事实上,我已经尝试了另一种方式。创建的视图控制器和你的方法的协议和委托方法到AppDelegate.m,包括我的当前视图控制器的.h文件在AppDelegate.h宣布协议,现在xcode给出奇怪的错误“”无法找到协议声明...... ....“”“。 – goks

+0

谢谢你从答案中得到了一个主意......现在工作 – goks

0

您可以使用KVO观察upcomingcount中的更改并更新徽章值。

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{ 

     if ([keyPath isEqualToString:NSStringFromSelector(@selector(upcomingcount))]) { 
      //SET BADGE VALUE HERE 

     } 

}