1

I was given a color as a hex STRING in my design specifications but in the Xcode project I am working on I need to give a hex of type INT to a UIColor extension.

The hex String I have is "#9B9B9B" but it somehow needs to become the Int representation of the same color because in the project UIColor has an extension (see below) that requires (hexInt: Int) and the given hex codes in the project have a format such as 0x212120.

How can I convert any given hex string into an Int for this extension??

extension UIColor {
    init(hexInt: Int) {
        self.init(
            red: CGFloat((hex >> 16) & 0xff) / 255,
            green: CGFloat((hex >> 8) & 0xff) / 255,
            blue: CGFloat(hex & 0xff) / 255,
            alpha: CGFloat(1))
    }
}

HangarRash
  • 7,314
  • 5
  • 5
  • 32
Jake Smith
  • 580
  • 3
  • 11

1 Answers1

3

You can easily convert a hex string with leading # into an Int by using:

let colorString = "#9B9B9B"
if let code = Int(colorString.dropFirst(), radix: 16) {
    // use the Int value as needed
} else {
    // the color string wasn't valid
}

Perhaps you can add an additional init to your UIColor extension:

convenience init?(code: String) {
    if let hex = Int(code.dropFirst(), radix: 16) {
        self.init(hexInt: hex)
    } else {
        return nil
    }
}
HangarRash
  • 7,314
  • 5
  • 5
  • 32