Search code examples
iosswiftuicolor

barTintColor in swift


what will be the best way to change navigation bar color in case all i have is an hex color: #292e3f

its work fine with something like that:

UINavigationBar.appearance().barTintColor = UIColor.blueColor()

but i cant figure out how to insert a hex, i tried usin this site:

http://www.touch-code-magazine.com/web-color-to-uicolor-convertor/

but it dosent seems to work:

var navBarColor = UIColor (red:0.161,green:0.18,blue:0.247,alpha:1.0)
UINavigationBar.appearance().barTintColor = navBarColor

Solution

  • You can create your own custom hex extension to accomplish this fairly easily. For instance something like this may work:

    extension UIColor {
         convenience init(hex: Int) {
                let r = hex / 0x10000
                let g = (hex - r*0x10000) / 0x100
                let b = hex - r*0x10000 - g*0x100
                self.init(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: 1)
            }
    }
    

    Then you can call it like:

    UINavigationBar.appearance().barTintColor = UIColor(hex: 0x292e3f)
    

    To get the hex color you want.