【发布时间】: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)默认radix为10)。问题是,您首先需要摆脱0x。为此,您可以使用String#dropFirst(_:Int)删除前 2 个字符,例如Int("0xe7c79d".dropFirst(2), radix: 16) -
为什么要去掉“0x”?
-
因为与
int的对话无法使用它
标签: swift string type-conversion hex uicolor