swift UITabbaritem colors

10,045

Solution 1

A UITabBar has a tintColor property, but this sets the tint for the selected image, not the unselected one. You're setting the unselected image correctly AFAIK. For changing the colour of the selected image, you can use the tintColor on the UITabBar (if you want all the images to have the same tint), or set your UITabBarItem's selectedImage with the rendering mode as AlwaysOriginal.

tabBarItem.selectedImage = UIImage(named: "first-selected")!.imageWithRenderingMode(.AlwaysOriginal)

I've set the UIImage to be an unwrapped optional because you probably want it to crash if there is no image file. It'll help ensure your images are actually being loaded, rather than silently failing :-)

You may also want to set the colour for the label or your text won't match your image colours. The below sets the defaults for all UITabBarItem's, but you can set (or override) it on a per item basis.

UITabBarItem.appearance().setTitleTextAttributes({NSForegroundColorAttributeName: UIColor.blueColor()}, forState:.Selected)
UITabBarItem.appearance().setTitleTextAttributes({NSForegroundColorAttributeName: UIColor.redColor()}, forState:.Normal)

Solution 2

Here's how you do it in swift 3 / 4

  UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blue], for: .selected)
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .normal)

Solution 3

If you want:

  • a selected tabBarItem to display a colour image
  • an unselected tabBarItem to display a greyed-out image

Then you need to ensure the relevant image assets in XCode are set as Render as: Default, then:

let image = SomeImage
tabBarItem.image = image
tabBarItem.selectedImage = image.withRenderingMode(.alwaysOriginal)

This ensures that for the selectedImage case you are forcing the image to display as the original, and in any other situation it will render with the expected tints applied.

Share:
10,045
Marianna
Author by

Marianna

Updated on July 28, 2022

Comments

  • Marianna
    Marianna almost 2 years

    I'm trying to figure out how to use the colors I want for my tabBar.

    I know how to change the background, I also know how to change the tabbar.item colors and text but I can't understand how to:

    • the default gray color of the unselected tab bar item
    • to change the color if the item is selected (and I'm using rendering mode always original cause I can't find another way to remove the default gray color from the non selected tab bar item)

      override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
      
          super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
      
          tabBarItem.title = "test"
          tabBarItem.image = UIImage(named: "first.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)   
      
      }
      

    how can I use the color I want, in the state I want?