4

I am trying to custom my UITabBarController. I have it embedded in my UIViewController, I also created a class for this UITabBarController.

override func viewDidLoad() {
    super.viewDidLoad()

    //custom tab bar
    self.tabBar.barTintColor = UIColor(red: 0.0/255.0, green: 102.0/255.0, blue: 153.0/255.0, alpha: 1)
    self.tabBar.tintColor = UIColor(red: 171.0/255.0, green: 203.0/255.0, blue: 61.0/255.0, alpha: 1)
    self.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:UIControlState.Normal)
    self.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:UIControlState.Disabled)

    for item in self.tabBar.items as [UITabBarItem]
    {
        item.image = item.selectedImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
    }


    // Do any additional setup after loading the view.
}

setTitleTextAttributes doesn't have any effects on the tab bar item. Can somebody please help me to find where the error is?

Cesare
  • 9,139
  • 16
  • 78
  • 130
Chongzl
  • 589
  • 1
  • 9
  • 25

2 Answers2

10

Here is the code that works in this case to put still in the UITabBarController:

override func viewDidLoad() {
super.viewDidLoad()

//custom tab bar
self.tabBar.barTintColor = UIColor(red: 0.0/255.0, green: 102.0/255.0, blue: 153.0/255.0, alpha: 1)
self.tabBar.tintColor = UIColor(red: 171.0/255.0, green: 203.0/255.0, blue: 61.0/255.0, alpha: 1)

for item in self.tabBar.items as [UITabBarItem]
{
    item.image = item.selectedImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
item.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:UIControlState.Normal)
    item.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:UIControlState.Disabled)
    item.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor(red: 171.0/255.0, green: 203.0/255.0, blue: 61.0/255.0, alpha: 1)], forState:UIControlState.Selected)
}
}
Chongzl
  • 589
  • 1
  • 9
  • 25
0

The tab bar items belong to the individual child view controllers, so you need to change the attributes in those controllers, not the tab bar controller.

rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • I tried to change the attributes in controllers in the viewdidload, when the 1° view is load, the tab bar item of the 2° is still ios default color which is grey, only if I click on the 2° view its tab bar item is set with the right color. Can you please explain in more detail where I have to put the codes? – Chongzl Jan 29 '15 at 08:17
  • 1
    @Chongzl, put the code in awakeFromNib instead. viewDidLoad is not called on any controllers other than the first one, until you click on their tab. – rdelmar Jan 29 '15 at 16:30