Is it possible to change UITabBarItem badge color

前端 未结 14 1640
别那么骄傲
别那么骄傲 2020-12-05 00:14

I want to change background color of UITabBarItem badge but can\'t find any resource on how to make it.

14条回答
  •  盖世英雄少女心
    2020-12-05 01:03

    No you can't change the color but you can use your own badges instead. 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.

    extension UITabBarController {
        func setBadges(badgeValues:[Int]){
    
            var labelExistsForIndex = [Bool]()
    
            for value in badgeValues {
                labelExistsForIndex.append(false)
            }
    
            for view in self.tabBar.subviews {
                if view.isKindOfClass(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 var i=0;i 0 {
                        addBadge(i, value: badgeValues[i], color:UIColor(red: 4/255, green: 110/255, blue: 188/255, alpha: 1), 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 = 12
            let yOffset:CGFloat = -9
    
            var badgeView = PGTabBadge()
            badgeView.frame.size=CGSizeMake(17, 17)
            badgeView.center=CGPointMake((itemWidth * itemPosition)-(itemWidth/2)+xOffset, 20+yOffset)
            badgeView.layer.cornerRadius=badgeView.bounds.width/2
            badgeView.clipsToBounds=true
            badgeView.textColor=UIColor.whiteColor()
            badgeView.textAlignment = .Center
            badgeView.font = font
            badgeView.text = String(value)
            badgeView.backgroundColor = bgColor
            badgeView.tag=index
            tabBar.addSubview(badgeView)
    
        }
    }
    
    class PGTabBadge: UILabel {
    
    }
    

提交回复
热议问题