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))
    }
}

1

1 Answer 1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.