首页 > 解决方案 > 在 iOS 12 中更改 UITabBarItem 徽章字体

问题描述

我想更改我的 tabbarItem 徽章字体,我尝试使用这个答案来做到这一点,但正如评论中所说,它适用于 iOS 10,但在 iOS 11 中存在问题。我试图在 iOS 12 中使用 swift 4 但它不起作用。

UITabBarItem.appearance().setBadgeTextAttributes([NSAttributedStringKey.font.rawValue: UIFont(name: "IRANSans-Bold", size: 14) as Any], for: .normal)

请让我知道是否有任何方法可以执行此操作,或者我需要为此创建一个自定义类。

标签: iosswiftuitabbaritembadge

解决方案


我搜索了很多,发现无法更改标签栏项目徽章字体。因此,我为 UITabBarController 编写了一个扩展,如下所示:

    func setCustomBadge(){
    removeMyCustomBadge(view: self.tabBar)
    setBadgeLabel(view: self.tabBar)
}
func setBadgeLabel(view:UIView){
    for subview in (view.subviews){
        let myType = String(describing: type(of: subview))
        print(myType)
        if myType == "_UIBadgeView" {
          let customBadeg : UILabel = UILabel(frame: CGRect(x: subview.frame.origin.x, y: subview.frame.origin.y, width: subview.frame.size.width, height: subview.frame.size.height))
            customBadeg.font = UIFont(name: "IRANSans", size: 10)
            customBadeg.layer.masksToBounds = true
            customBadeg.layer.cornerRadius = customBadeg.frame.size.height/2
            customBadeg.textAlignment = .center
            customBadeg.textColor = UIColor.white
            customBadeg.backgroundColor = UIColor(named: "Red")
            customBadeg.text = Utility().enNums2Fa(inputString: String(format: "%d", Utility().retrieveUserBasketBadge()))
            view.addSubview(customBadeg)
            subview.isHidden = true
        }
        else {
            setBadgeLabel(view:subview)
        }
    }
  }
} 

推荐阅读