Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cant convert string hex into hexint and then into UIColor

I have JSON Data with an array of strings. When I decode this data I need to convert strings into ints and then use it for creating UIColors. But when I convert my hexadecimal from string to int it returns me the wrong color.
Here the code

struct DrawingElement {
    let colorsForCells: [UIColor]
}

extension DrawingElement: Decodable {
    
    enum CodingKeys: String, CodingKey {
        case colorsForCells = "cells"
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        let rawColors = try container.decode([String].self, forKey: .colorsForCells)
        colorsForCells = rawColors.map {
            
            let value = Int($0)
            let color = uiColorFromHex(rgbValue: value ?? 77)
            return color == .black ? .white : color
            
        }
    }
   
}
func uiColorFromHex(rgbValue: Int) -> UIColor {
    
    let red =   CGFloat((rgbValue & 0xFF0000) >> 16) / 0xFF
    let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 0xFF
    let blue =  CGFloat(rgbValue & 0x0000FF) / 0xFF
    let alpha = CGFloat(1.0)
    
    return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}

Example of my string in Data: "0xe7c79d"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have to remove the 0x prefix and then specify the radix 16:

let s = "0xe7c79d"
print(Int(s)) // nil

let value = s.hasPrefix("0x")
    ? String(s.dropFirst(2))
    : s
print(Int(value, radix: 16)) // 15189917
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading