Change TabBarItem title font to bold in Swift for iOS

前端 未结 6 690
执念已碎
执念已碎 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:47

    To set the TitleTextAttribute, you should use the appearance proxy like: [UIBarItem appearance]

    0 讨论(0)
  • 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)
        }
      }
    
    }
    
    0 讨论(0)
  • 2020-12-18 05:58

    The problem is that the state of tabBarItem0 is not changed to Selected. Because this is UITabBarItem which represents a single element of a UITabBar. So, you can not directly change the status using UITabBarItem API. You have to change it state by assigning selectedItem.

    This information is gained from documentation and I suggest all programmers to have skills like this. Hopefully, this will help.

    0 讨论(0)
  • 2020-12-18 05:59

    FOUND THE SOLUTION (Swift 3, XCode 8.1)

    1. In Storyboard, give a unique Tag to each UITabBarItem you have: For every tab -> Select it and go to it's "Attributes Inspector" -> Give each one a unique number in the "Tag" field but you should not use zero (I used 1 through 4).

      This sets us up for later, to identify which tab is pressed.


    1. Create a new subclass of UITabBarController and then assign it: FILE -> New File -> iOS Cocoa Touch -> create a Subclass of UITabBarController. Assign the new .swift file to your UITabBarController under "Identity Inspector."

      We will need custom logic in our UITabBarController.


    1. Create a new subclass of UITabBarItem, assign the same file to all of your UITabBarItems: FILE -> New File -> iOS Cocoa Touch -> create a Subclass of UITabBarItem and assign the same one to all of your tabs.

      We will need a shared custom logic in our tab bar items.


    1. Add this code to your UITabBarItem subclass, it sets up the initial state (primary tab bold, the rest unselected) and will allow for programmatic tab changes as well:

      class MyUITabBarItemSubclass: UITabBarItem {
      
          //choose initial state fonts and weights here
          let normalTitleFont = UIFont.systemFont(ofSize: 12, weight: UIFontWeightRegular) 
          let selectedTitleFont = UIFont.systemFont(ofSize: 12, weight: UIFontWeightBold)
      
          //choose initial state colors here
          let normalTitleColor = UIColor.gray 
          let selectedTitleColor = UIColor.black
      
          //assigns the proper initial state logic when each tab instantiates 
          override func awakeFromNib() {
              super.awakeFromNib()
      
              //this tag # should be your primary tab's Tag* 
              if self.tag == 1 { 
                  self.setTitleTextAttributes([NSFontAttributeName: selectedTitleFont, NSForegroundColorAttributeName: selectedTitleColor], for: UIControlState.normal)
              } else {
                  self.setTitleTextAttributes([NSFontAttributeName: normalTitleFont, NSForegroundColorAttributeName: normalTitleColor], for: UIControlState.normal)
              }
      
          }
      
      }
      

    Here we set up the initial state so that the tabs are set correctly when the app opens up, we'll take care of the physical tab presses in the next subclass.


    1. Add this code to your UITabBarController subclass, it's the logic for assigning the correct states as you press on the tabs.

      class MyUITabBarControllerSubclass: UITabBarController {
      
          //choose normal and selected fonts here
          let normalTitleFont = UIFont.systemFont(ofSize: 12, weight: UIFontWeightRegular)
          let selectedTitleFont = UIFont.systemFont(ofSize: 12, weight: UIFontWeightBold)
      
          //choose normal and selected colors here
          let normalTitleColor = UIColor.gray
          let selectedTitleColor = UIColor.black
      
      
          //the following is a delegate method from the UITabBar protocol that's available 
          //to UITabBarController automatically. It sends us information every
          //time a tab is pressed. Since we Tagged our tabs earlier, we'll know which one was pressed,
          //and pass that identifier into a function to set our button states for us
      
          override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
              setButtonStates(itemTag: item.tag)
          }
      
      
          //the function takes the tabBar.tag as an Int
          func setButtonStates (itemTag: Int) {
      
              //making an array of all the tabs
              let tabs = self.tabBar.items
      
              //looping through and setting the states
              var x = 0
              while x < (tabs?.count)! {
      
                  if tabs?[x].tag == itemTag {
                      tabs?[x].setTitleTextAttributes([NSFontAttributeName: selectedTitleFont, NSForegroundColorAttributeName: selectedTitleColor], for: UIControlState.normal)
                  } else {
                      tabs?[x].setTitleTextAttributes([NSFontAttributeName: normalTitleFont, NSForegroundColorAttributeName: normalTitleColor], for: UIControlState.normal)
                  }
      
                  x += 1
      
              }
      
          }
      
      }
      

    It looks like this was such a pain because for some reason the tabs do not recognize state changes into ".Selected". We had to do everything by working with .Normal states only - basically detecting the state changes ourselves.


    1. You can programmatically change the tabs and still detect state changes by... I'll update this later if anyone has an interest, just ask.

    Hope this helped!

    0 讨论(0)
  • 2020-12-18 05:59
    UITabBarItem.appearance().setTitleTextAttributes(
            [NSFontAttributeName: UIFont(name:"your_font_name", size:11)!, 
                NSForegroundColorAttributeName: UIColor(rgb: 0x929292)], 
            forState: .Normal)
    
    0 讨论(0)
  • 2020-12-18 05:59

    Build Settings\Swift Language Version: 4.1

    General\Deployment Target: 10.3

    import UIKit
    
    class FirstViewController: UIViewController {
    
      override func viewDidLoad() {
        super.viewDidLoad()
    
        let attrsNormal = [NSAttributedStringKey.foregroundColor : UIColor.black,
                     NSAttributedStringKey.font : UIFont(name: "Arial", size: 14)!]
        UITabBarItem.appearance().setTitleTextAttributes(attrsNormal,
                                                         for: UIControlState.normal)
    
        let attrsSelected = [NSAttributedStringKey.foregroundColor : UIColor.red,
                           NSAttributedStringKey.font : UIFont(name: "Arial", size: 14)!]
        UITabBarItem.appearance().setTitleTextAttributes(attrsSelected,
                                                         for: UIControlState.selected)
      }
      ...
    }
    
    0 讨论(0)
提交回复
热议问题