lifewithelliott lifewithelliott - 1 month ago 4x
Swift Question

Swift - Custom color not applying to barTintColor

In a view controller embedded in a navigation controller I am attempting to change the

to a custom color. What I have experienced is if I use a default color such as the one below, the color is actually applied:

self.navigationController?.navigationBar.barTintColor = UIColor.blackColor()

However when I try to create an instance of my own custom color such as this code would show, the color is not applied:

let customRedColor = UIColor( red: 255, green: 0, blue: 13, alpha: 1 )
self.navigationController?.navigationBar.barTintColor = customRedColor

I am very curious as to why the custom color is not being applied to the navigation bar so that leads me to ask:

What approach should be taken in order to correctly apply a custom color to the navigation bars barTintColor property.


You need to give color by dividing them by 255, the syntax is like this.

init(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)

Each of the ones that take a CGFloat take a value between 0.0 and 1.0, referring to either the complete absence of, or the maximum amount of that color component respectively. So, this means that even if you have pure RGB values in decimal or hexadecimal format, you will have to divide them by decimal 255 to get the amount to input here.

let customRedColor = UIColor(red: 255/255 , green: 0, blue: 13/255, alpha: 1.0)
//or Direct
let customRedColor = UIColor(red: 1.0 , green: 0, blue: 0.05, alpha: 1.0)
self.navigationController?.navigationBar.barTintColor = customRedColor