Marianna
Marianna

Reputation: 133

swift UITabbaritem colors

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:

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

Upvotes: 7

Views: 10300

Answers (3)

justsee
justsee

Reputation: 933

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.

Upvotes: 1

John Riselvato
John Riselvato

Reputation: 12904

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)

Upvotes: 5

rickerbh
rickerbh

Reputation: 9911

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)

Upvotes: 11

Related Questions