4

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];
                }
            }
        }
    }
}
CrazyDeveloper
  • 995
  • 1
  • 13
  • 24

6 Answers6

4

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];
CrazyDeveloper
  • 995
  • 1
  • 13
  • 24
3

For Swift, this one works on any screen size and any orientation.

extension UITabBarController {

    func setBadges(badgeValues: [Int]) {

        for view in self.tabBar.subviews {
            if view is CustomTabBadge {
                view.removeFromSuperview()
            }
        }

        for index in 0...badgeValues.count-1 {
            if badgeValues[index] != 0 {
                addBadge(index, value: badgeValues[index], color:UIColor(paletteItem: .Accent), font: UIFont(name: Constants.ThemeApp.regularFontName, size: 11)!)
            }
        }
    }

    func addBadge(index: Int, value: Int, color: UIColor, font: UIFont) {
        let badgeView = CustomTabBadge()

        badgeView.clipsToBounds = true
        badgeView.textColor = UIColor.whiteColor()
        badgeView.textAlignment = .Center
        badgeView.font = font
        badgeView.text = String(value)
        badgeView.backgroundColor = color
        badgeView.tag = index
        tabBar.addSubview(badgeView)

        self.positionBadges()
    }

    override public func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.tabBar.setNeedsLayout()
        self.tabBar.layoutIfNeeded()
        self.positionBadges()
    }

    // Positioning
    func positionBadges() {

    var tabbarButtons = self.tabBar.subviews.filter { (view: UIView) -> Bool in
        return view.userInteractionEnabled // only UITabBarButton are userInteractionEnabled
    }

    tabbarButtons = tabbarButtons.sort({ $0.frame.origin.x < $1.frame.origin.x })

        for view in self.tabBar.subviews {
            if view is CustomTabBadge {
                let badgeView = view as! CustomTabBadge
                self.positionBadge(badgeView, items:tabbarButtons, index: badgeView.tag)
            }
        }
    }

    func positionBadge(badgeView: UIView, items: [UIView], index: Int) {

        let itemView = items[index]
        let center = itemView.center

        let xOffset: CGFloat = 12
        let yOffset: CGFloat = -14
        badgeView.frame.size = CGSizeMake(17, 17)
        badgeView.center = CGPointMake(center.x + xOffset, center.y + yOffset)
        badgeView.layer.cornerRadius = badgeView.bounds.width/2
        tabBar.bringSubviewToFront(badgeView)
    }
}

class CustomTabBadge: UILabel {}
Alexis C.
  • 4,898
  • 1
  • 31
  • 43
  • Code works but you have to order tabbarItems by position: tabbarButtons.sort({ $0.frame.origin.x < $1.frame.origin.x }) – agfa555 Mar 25 '16 at 07:13
  • Did you have issues? Because they always were sorted by defaults from what I experienced. – Alexis C. Mar 25 '16 at 10:09
  • Yes, they came differently than the normal order, might be something recent from Swift or Xcode. – agfa555 Mar 25 '16 at 12:25
3

Try this code iOS 10:

[[[self tabBarController].viewControllers objectAtIndex:1] tabBarItem].badgeColor = [UIColor greenColor];
Vitaly Potlov
  • 365
  • 1
  • 7
  • 14
1

You should create a custom tab bar item class and do the customization there. You can find many article/code for creating custom tab bar.

Example: How to create a fully customized tab bar in your iOS App

Otherwise, you will have to create workarounds and hacks that may just break or don't work.

Rafał Sroka
  • 39,540
  • 23
  • 113
  • 143
0

In Swift language I used below code and it works Thanks to CrazyDeveloper

var tbc: UITabBarController = storyboard.instantiateViewControllerWithIdentifier("TabBarController") as! UITabBarController
            self.window?.rootViewController = tbc
            var array = tbc.tabBar.subviews as Array

        if lblNotificationBadge == nil{
            lblNotificationBadge = UILabel(frame: CGRectMake(36, 2, 15, 15))
            lblNotificationBadge!.textAlignment = NSTextAlignment.Center
            lblNotificationBadge!.font = UIFont(name:"Montserrat-Light", size:10)
            lblNotificationBadge!.textColor = UIColor.whiteColor()
            lblNotificationBadge!.backgroundColor = UIColor(red: 30/255, green: 177/255, blue: 71/255, alpha: 1)
            lblNotificationBadge!.layer.cornerRadius = 7
            lblNotificationBadge!.clipsToBounds = true
            array[2].addSubview(lblNotificationBadge!)
        }

        lblNotificationBadge!.text = "4"
Coder_A_D
  • 340
  • 5
  • 20
0

Use this code :

-(void) setBadge : (int) itemCount : (UITabBarController *) tabBarController {

    // first removing the prevues badge if added
    NSArray *viewsToRemove = [tabBarController.tabBar subviews];
    for (UIView *v in viewsToRemove) {
        if(v.tag == 999)
            [v removeFromSuperview];
    }

    // now if count is not equal to 0 adding a new badge to your tabbar
    if(itemCount != 0){
        UILabel *badge = [UILabel new];
        badge.text = [NSString stringWithFormat:@"%i" , itemCount];
        badge.font = [UIFont fontWithName:@"Custom font" size:10];
        badge.textAlignment=NSTextAlignmentCenter;
        badge.frame=CGRectMake(([[UIScreen mainScreen] bounds].size.width/2), 4, 16 , 16);
        badge.textColor=[UIColor whiteColor];
        badge.backgroundColor = [UIColor redColor];;
        badge.layer.cornerRadius=8;
        badge.clipsToBounds = YES;
        badge.tag = 999;
        [tabBarController.tabBar addSubview:badge];
    }
}

and then easily call it like this :

[self setBadge:1 :self.tabBarController];
Rudi
  • 4,304
  • 4
  • 34
  • 44