Search code examples
iosios7uitabbaritem

UITabBarItem change badge colour in iOS 7.1


Hi I am trying to change badge colour of UITabBarItem. Below is the code that I am using to achieve the same. The below code works in iOS 7.0. But it is not working in iOS 7.1. Any Help is appreciated.

for (UIView* tabBarButton in _tabbar.subviews) {
    for (UIView* badgeView in tabBarButton.subviews) {
        NSString* className = NSStringFromClass([badgeView class]);  
        // looking for _UIBadgeView
        if ([className rangeOfString:@"BadgeView"].location != NSNotFound) {
            for (UIView* badgeSubview in badgeView.subviews) {
                NSString* className = NSStringFromClass([badgeSubview class]);

                // looking for _UIBadgeBackground
                if ([className rangeOfString:@"BadgeBackground"].location != NSNotFound) {
                    @try {
                        NSLog(@"*******************BADGE IMAGE SET *******************");
                        [badgeSubview setValue:[UIImage imageNamed:@"count_bg.png"] forKey:@"image"];
                        //[badgeSubview setTintColor:[UIColor greenColor]];
                    }
                    @catch (NSException *exception) {}
                }

                if ([badgeSubview isKindOfClass:[UILabel class]]) {
                    ((UILabel *)badgeSubview).textColor = [UIColor whiteColor];
                }
            }
        }
    }
}

Solution

  • Finally I added a label with desired colour to tabBar and got the expected results.

        UILabel *badge=[[UILabel alloc]init];
        badge.text = @"2";
        badge.textAlignment=NSTextAlignmentCenter;
        badge.frame=CGRectMake(122, 1, 20, 20);
        badge.layer.cornerRadius=10;
        badge.textColor=[UIColor whiteColor];
        badge.backgroundColor=[UIColor greenColor];
        [tabbar addSubview:badge];