iOS tabBarItem徽章值从任何视图

时间:2016-07-27 12:30:00

标签: ios objective-c uitabbarcontroller uitabbaritem

我正在使用Objective c开发iOS应用程序。在我的应用程序中,如果用户未注册,则注册视图控制器为rootViewController。如果用户是注册,则tabBarController有三个选项卡rootViewController。我必须从任何视图控制器设置tabBarItem徽章值。假设我在第三个选项卡上并且它与另一个视图控制器有segue并且我在该视图控制器上,我必须从这里更改第一个视图控制器的tabBarItem徽章值。在我的情况下,tabBarItem徽章值更新只有我在使用

时转到该选项卡
NSString *upcomingcount=[NSString stringWithFormat:@"%lu",(unsigned long)self.arrbadge.count];
            self.navigationController.tabBarItem.badgeValue=upcomingcount;

在viewwillappear。

有没有办法从任何ViewController设置badgeValue?我想更新任何ViewController

的徽章价值

3 个答案:

答案 0 :(得分:1)

plz在您的app delegate中使用此方法

 - (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];

答案 1 :(得分: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

        }

}

答案 2 :(得分:0)

func setBadge(){
        let viewconrollers = self.tabBarController?.viewControllers
        viewconrollers![3].tabBarItem.badgeValue = "Your String value"
        viewconrollers![3].tabBarItem.badgeColor = UIColor.green
    }


//call setBadge() method from view controller's viewdidload method.

// select your give number it the view controllers array for providing badge on the desired tab