I am trying to change the tab bar color in a view controller in XCode using swift. I have a hex that I matched up to an RGB value and I am trying to set that in this code. (Which does not work)
let color = UIColor(red: 41, green: 40, blue: 39, alpha: 1.0)
UITabBar.appearance().barTintColor = color
However this code does:
UITabBar.appearance().barTintColor = UIColor.whiteColor()
Can anyone explain why this doesn't work, and what I can do to fix it?
It doesn't work because all of your RGB components are greater than 1, which is the maximum available value per-channel. You're probably thinking of the color channels as bytes, but that wouldn't scale to varying color bit depths. (For example, it was common to render to RGB565, not RGBA8888 in early versions of iOS. And you can probably expect Apple to make screens with 16-bit accuracy the norm, in the near future.) Floats from 0 to 1 are employed, to divorce the bit depth from the color representation.
https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UIColor_Class/index.html#//apple_ref/occ/instm/UIColor/initWithRed:green:blue:alpha:
To use RGB values, just divide them by 255.0
. This will produce a float value between 0 and 1.
let color = UIColor(red: 41.0/255.0, green: 40.0/255.0, blue: 39.0/255.0, alpha: 1.0)
iOS 10 Swift 3.0
If you don't mind to use swift frameworks then us UINeraida to change Tabbar background as UIColor
or HexColor
or UIImage
and change complete forground color.
For UITabBar
neraida.tabbar.background.color.uiColor(UIColor.orange, isTranslucent: false, viewController: self)
//change tab bar tint color //(select,unselect)
neraida.tabbar.foreground.color.uiColor((UIColor.white,UIColor.green), viewController: self)
//set Background Image for tab bar
neraida.tabbar.background.image("background", isTranslucent: false, viewController: self)