0

enter image description here

I'd like to put a background color for just the title of TabBar using swift I tried to use NSAttributedString.Key.backgroundColor but it not appears color in the background.

Can anybody help me to change the background color for just the title of TabBar?

I need to add yellow color to the background to title in the normal state not selected.

Parth Patel
  • 915
  • 11
  • 33
  • 1
    please share code where you're assigning the title – rkyr Jul 15 '19 at 08:25
  • 1
    Possible duplicate of [Set navbar title background color (swift)](https://stackoverflow.com/questions/37558042/set-navbar-title-background-color-swift) – Wolfgang Jul 15 '19 at 08:42

2 Answers2

1
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.white], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.gray], for: .selected)

This works for a single item. If you'd like to change the color for all items in the tab bar, try parsing through them like such

for item in self.tabBar.items! {

      item.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.white], for: .normal)
      item.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.gray], for: .selected)

    } 
  • thanks for your answer ...but I need to know how to change the background color of title not to change the title color .. – IosMohammed Jul 15 '19 at 09:14
  • @IosMohammed I just now understand what you want to do. I would suggest creating a custom View for the tab bar title in which you can add a label over a background view. The default title doe snot support the behavior you are expecting. Doing this will result in a fully customizable background view, from rounding corners to gradients, you name it. – Tudor Andreescu Jul 15 '19 at 11:51
0

you can add the following code snippet to your viewDidLoad:

UITabBar.appearance().barTintColor = UIColor.black // your color
Ewurafua Plange
  • 627
  • 1
  • 7
  • 20