How can I convert RGB hex value into UIColor in Swift?

Viewed 70

I tried converting the following Objective -C code block to Swift using Swiftify.

#define HEXCOLOR(hex) [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16)) / 255.0 green:((float)((hex & 0xFF00) >> 8)) / 255.0 blue:((float)(hex & 0xFF)) / 255.0 alpha:1]

This code is called as:

_contentView.backgroundColor = HEXCOLOR(0x24B491);

Here is the converted code output

func HEXCOLOR(_ hex: Any) -> UIColor {
    UIColor(red: CGFloat((Float((hex & 0xff0000) >> 16)) / 255.0), green: CGFloat((Float((hex & 0xff00) >> 8)) / 255.0), blue: CGFloat((Float(hex & 0xff)) / 255.0), alpha: 1)
}

The code conversion seems correct in all parts except for the type of the function's input parameter.

P.S. There are many GitHub gists which convert hexString to UIColor.

1 Answers

You just need to change your hex parameter type from Any to unsigned integer. Btw no need to convert the values to Float.

func hexColor(_ hex: UInt) -> UIColor {
    UIColor(red: .init((hex & 0xff0000) >> 16) / 255,
          green: .init((hex & 0xff00)   >>  8) / 255,
          blue:  .init( hex & 0xff)            / 255,
          alpha: 1)
}

hexColor(0x24B491)   // r 0.141 g 0.706 b 0.569 a 1.0
Related