1

I add view controller background color in Attributes Inspector. The color is "00466E".

enter image description here


But, I add the color with code in one of my view controllers. I need to convert color code to Hexcolor.

var window_background: String! = "00466E"
window_background = match.value(forKey: "window_background") as! String
collectionview.backgroundColor = UIColor().HexToColor(hexString: window_background)<br>

After I add this code and run the project, the background color result is not the one I want.
It changes a little bit.

enter image description here


Anyone can explain me how this color occurs when I add color convert code? Please help me.

May Phyu
  • 895
  • 3
  • 23
  • 47
  • `HexToColor(hexString:)` What's that method? – Larme May 02 '17 at 10:14
  • @May Phyu you can get RGB Color code of your color from storyboard and apply same rgb code in class. – Tushar Sharma May 02 '17 at 10:16
  • @Larme, I would like to convert the color code into string because when I get the color code(string) from server is "100" (for e.g..), then the app theme color including background color will change into other color. That it is. – May Phyu May 02 '17 at 10:21
  • Possible duplicate of [How to use hex colour values in Swift, iOS](http://stackoverflow.com/questions/24263007/how-to-use-hex-colour-values-in-swift-ios) – Larme May 02 '17 at 10:23
  • Check out this [solution](http://stackoverflow.com/questions/27628473/uinavigationbar-background-color-setted-from-storyboard-differ-from-the-color-se/27632680#27632680) too, may be it can help. – Kampai May 02 '17 at 11:27

1 Answers1

3

You can use it:

extension UIColor {

    convenience init(hex: Int) {
        let components = (
            R: CGFloat((hex >> 16) & 0xff) / 255,
            G: CGFloat((hex >> 08) & 0xff) / 255,
            B: CGFloat((hex >> 00) & 0xff) / 255
        )

        self.init(red: components.R, green: components.G, blue: components.B, alpha: 1)
    }

}

then while calling :

view.backgroundColor =  UIColor(hex:0x00466E)
ankit
  • 3,537
  • 1
  • 16
  • 32