0

I'm a bit new to Swift and I run into a problem that I can not solve. I have a String with a value that represents a hexadecimal, for example "#004080". This value comes directly from a database, and I want to use it to modify the color of a UIlabel, but I cannot do it.

This is my summary code:

...
let color1 = "004080"
...


//try do this:
plato1.textColor = UIColor(hex: color1)

//Error:
// Cannot convert value of type 'String' to expected argument type 'Int'

//Try this too:
plato1.textColor = UIColor(hex: Int(Color1)!)

//Error:
//This returns a different color: 4080, not 004080


//EXTENSION FOR A HEXADECIMAL
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)
    }
}

A little messy the hexadecimals with swift for me.

Any advice?

Thanks you!

Mimmetico
  • 422
  • 9
  • 25

1 Answers1

0

You could split your string into two-character-Strings that represent the RGB each individually. This would solve your problem with leading zeroes not being displayed.

vollkorntomate
  • 638
  • 1
  • 8
  • 17