Change TabBarItem title font to bold in Swift for iOS

前端 未结 6 695
执念已碎
执念已碎 2020-12-18 05:08

I\'m trying to set the font weight of a selected tab bar item to bold font. It seems as it has no effect. Any idea what is wrong. forState: .Normal works as exp

6条回答
  •  情书的邮戳
    2020-12-18 05:57

    I've faced the same issue when tried to change font of selected item. Looks like titleTextAttributes' font parameter is only useful when setting them to normal state. That's why I implemented UITabBarControllerDelegate where I update attributes for currently selected item. You should call updateSelection() method after UITabBarControllers loadView() too. Or you can call updateSelection() method in overridden selectedItem setter.

    extension TabBarController: UITabBarControllerDelegate {
    
      func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        updateSelection()
      }
    
      func updateSelection() {
        let normalFont = Fonts.Lato.light.withSize(10)
        let selectedFont = Fonts.Lato.bold.withSize(10)
        viewControllers?.forEach {
          let selected = $0 == self.selectedViewController
          $0.tabBarItem.setTitleTextAttributes([.font: selected ? selectedFont : normalFont], for: .normal)
        }
      }
    
    }
    

提交回复
热议问题