Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITabBar change background color of one UITabBarItem on iOS7

Can I change the background color of a specific UITabBarItem in a UITabBar?

I know how to change all the background of the selected background, using:

[[UITabBar appearance] setBarTintColor:[UIColor redColor]];
[[UITabBar appearance] setTintColor:[UIColor blueColor]];
[[UITabBar appearance] setSelectedImageTintColor:[UIColor yellowColor]];

But can it be done for only one item without subclassing?

Thanks

like image 325
Hugues BR Avatar asked Dec 05 '13 21:12

Hugues BR


People also ask

How do I change the background color of a tab bar in Swift?

backgroundColor = UIColor(red:1, green:0, blue:0, alpha:1) / UITabBar. appearance(). tintColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1) // New!! func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {...}


2 Answers

You can add a subview to the parent tabBar, and set a background color on the subview. You can use the tabBar frame dimensions to calculate the offset and width of your tabBarItem, and then insert the subview underneath.

Example (in Swift):

// Add background color to middle tabBarItem
let itemIndex = 2
let bgColor = UIColor(red: 0.08, green: 0.726, blue: 0.702, alpha: 1.0)

let itemWidth = tabBar.frame.width / CGFloat(tabBar.items!.count)
let bgView = UIView(frame: CGRectMake(itemWidth * itemIndex, 0, itemWidth, tabBar.frame.height))
bgView.backgroundColor = bgColor
tabBar.insertSubview(bgView, atIndex: 0)
like image 98
ndbroadbent Avatar answered Nov 28 '22 17:11

ndbroadbent


in Swift: This solution is for apps using Auto Layout . Main difference between other solution is that: tabBar.frame.width is not getting actual device's screen width. So, bgView is appearing wrong place.

You can fix it with this : UIScreen.main.bounds.width

let tabWidth: CGFloat = UIScreen.main.bounds.width / CGFloat(self.tabbar!.items!.count)
let tabIndex: CGFloat = 2
let bgColor: UIColor = .redColor
let bgView = UIView(frame: CGRectMake(tabWidth * tabIndex, 0, tabWidth, 49))
bgView.backgroundColor = bgColor
self.tabbar!.insertSubview(bgView, atIndex: 0)

49 is a default height of UITabbar

like image 30
fatihyildizhan Avatar answered Nov 28 '22 18:11

fatihyildizhan