【问题标题】:Cant convert string hex into hexint and then into UIColor [duplicate]无法将字符串十六进制转换为十六进制然后转换为 UIColor [重复]
【发布时间】:2022-01-31 11:38:02
【问题描述】:

我有带有字符串数组的 JSON 数据。当我解码这些数据时,我需要将字符串转换为整数,然后用它来创建 UIColors。但是,当我将十六进制从字符串转换为 int 时,它会返回错误的颜色。 代码在这里

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

我在数据中的字符串示例:“0xe7c79d”

【问题讨论】:

  • 您的第一个问题是,您不能使用Int(_:String) 将字符串值"0xe7c79d" 转换为int,这没有意义,默认情况下,它需要一个小数价值。幸运的是,他们认为。相反,您需要使用Int(_:String, radix: Int)(实际上Int(_:String) 默认radix10)。问题是,您首先需要摆脱0x。为此,您可以使用 String#dropFirst(_:Int) 删除前 2 个字符,例如 Int("0xe7c79d".dropFirst(2), radix: 16)
  • 为什么要去掉“0x”?
  • 因为与int 的对话无法使用它

标签: swift string type-conversion hex uicolor


【解决方案1】:

您必须删除 0x 前缀,然后指定基数 16:

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

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

【讨论】:

    猜你喜欢
    • 2018-01-22
    • 2012-08-06
    • 2018-01-31
    • 1970-01-01
    • 2013-02-07
    • 2011-05-15
    • 2019-01-17
    • 1970-01-01
    • 2014-12-15
    相关资源
    最近更新 更多