iOS - 从其他类更改标签栏徽章

问题描述 投票:3回答:4

我搜索了很多,但找不到答案,因此决定问你:)。

我有一些带有一些观点的应用程序。登录后,我创建了一个带有3个选项卡的UITabBarController。

现在,我希望根据用户拥有的通知数更改第二个标签的徽章。

在viewdidload方法中调用时,此核心工作:

NSString *badgeValue = [NSString stringWithFormat:@"%i", [cacheNotifications count]];
if([cacheNotifications count] != 0){
    [[[[[self tabBarController] viewControllers] objectAtIndex: 1] tabBarItem] setBadgeValue:badgeValue];
}

但是,我在后台运行一个守护进程,每30秒检查一次通知。如果我能从这个守护进程中更改徽章,那就太好了。

当我打电话给这样的话:

PlatformViewController *theInstance = [[PlatformViewController alloc] init];
    [theInstance updateNotificationsBadge];

它确实调用该函数但不更新徽章。有或没有performSelectorOnMainThread。

updateNotificationsBadge:

-(void) updateNotificationsBadge{
NSString *badgeValue = [NSString stringWithFormat:@"%i", [cacheNotifications count]];
NSLog(@"Length here is: %i", [cacheNotifications count]);
if([cacheNotifications count] > 0){
    NSLog(@"call..");
    [self performSelectorOnMainThread:@selector(setNotification:)
                                    withObject:badgeValue
                                 waitUntilDone:YES];


}

}

-(void)setNotification:(NSString*)badge{
NSLog(@"Called. %@", badge);
[[[[[self tabBarController] viewControllers] objectAtIndex: 1] tabBarItem] setBadgeValue:badge];

}

我怎么能解决这个问题?

提前致谢!

编辑:

cacheNotifications是globalVars.m中声明的全局变量。当我调用一个新实例时,它不会重新初始化。

我从daemonClass.m调用下面的代码

PlatformViewController *theInstance = [[PlatformViewController alloc] init];
[theInstance updateNotificationsBadge];
ios xcode tabbar badge
4个回答
1
投票

您需要使用现有引用,而不是为platformViewController创建新实例。当你创建一个新的时候,cacheNotification数组不会是initialized,也不会是contents。所以它总会返回0。

UITabBarController是一个containerViewController包含所有viewControllers。因此,您无需更改其他类中的选项卡badgeValue。您可以从任何类更改它。

在你的setNotification:方法中,像这样改变badgeValue

[[[[self tabBarController] tabBar] items] objectAtIndex:1] setBadgeValue:badge];

0
投票

您应该使用相同的类实例而不是创建新实例。这破坏了之前的价值。我建议您在获得徽章时使用NSNotificationCenter发布通知,该徽章将在platformViewControllerclass中实现徽章的void getter和setter方法。然后没有实例会被破坏。

希望这可以帮助


0
投票

我真的不知道你的问题,但我认为我会使用nsobject的子类,并在每个viewController中我都会更改徽章。类似的东西:https://stackoverflow.com/a/9736559/2000162


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
© www.soinside.com 2019 - 2024. All rights reserved.