Is it possible to customize UITabBarItem Badge?

Michelle Ybanez picture Michelle Ybanez · Apr 29, 2013 · Viewed 15.1k times · Source

The question below is similar as mine.

How to use a custom UIImage as an UITabBarItem Badge?

Is it possible to use a background image instead of drawing it myself? I think it's fine since my app will only use a 1-digit badgeValue.

If it is not really possible, I want to know if we can change the badge color instead. The answers in the question below are not really helping.

Is it possible to change UITabBarItem badge color

Answer

TimWhiting picture TimWhiting · Aug 30, 2015

This is your best bet. Add this extension at the file scope and you can customise the badges however you like. Just call self.tabBarController!.setBadges([1,0,2]) in any of your root view controllers.

To be clear that is for a tab bar with three items, with the badge values going from left to right.

If you want to add images instead just change the addBadge method

extension UITabBarController {
    
    func setBadges(badgeValues: [Int]) {

        var labelExistsForIndex = [Bool]()

        for _ in badgeValues {
            labelExistsForIndex.append(false)
        }

        for view in self.tabBar.subviews where view is PGTabBadge {
            let badgeView = view as! PGTabBadge
            let index = badgeView.tag
            
            if badgeValues[index] == 0 {
                badgeView.removeFromSuperview()
            }
            
            labelExistsForIndex[index] = true
            badgeView.text = String(badgeValues[index])
        }

        for i in 0...(labelExistsForIndex.count - 1) where !labelExistsForIndex[i] && (badgeValues[i] > 0) {
            addBadge(index: i, value: badgeValues[i], color: .red, font: UIFont(name: "Helvetica-Light", size: 11)!)
        }

    }

    func addBadge(index: Int, value: Int, color: UIColor, font: UIFont) {

        let itemPosition = CGFloat(index + 1)
        let itemWidth: CGFloat = tabBar.frame.width / CGFloat(tabBar.items!.count)

        let bgColor = color

        let xOffset: CGFloat = 5
        let yOffset: CGFloat = -12

        let badgeView = PGTabBadge()
        badgeView.frame.size =  CGSize(width: 12, height: 12)
        badgeView.center = CGPoint(x: (itemWidth * itemPosition) - (itemWidth / 2) + xOffset, y: 20 + yOffset)
        badgeView.layer.cornerRadius = badgeView.bounds.width/2
        badgeView.clipsToBounds = true
        badgeView.textColor = UIColor.white
        badgeView.textAlignment = .center
        badgeView.font = font
        badgeView.text = String(value)
        badgeView.backgroundColor = bgColor
        badgeView.tag = index
        tabBar.addSubview(badgeView)

    }
}
    
class PGTabBadge: UILabel { }