【发布时间】:2019-06-15 12:01:45
【问题描述】:
例如,下面的代码适用于 UIColor.Purple 或 UIColor.Yellow,但是当我使用 UIColor.black 时应用程序崩溃。
致命错误:索引超出范围 使用 UIColor.black 时,似乎组件 [2] 和 [3] 不存在。我知道我在强制展开,但不是所有颜色都有 RGBA 吗?
//UIColor RGBA to string
public extension UIColor {
class func StringFromUIColor(color: UIColor) -> String{
let components = color.cgColor.components
return "[\(components![0]), \(components![1]), \(components![2]), \(components![3])]"
}
class func UIColorFromString(string: String) -> UIColor {
let componentsStringStepOne = string.replacingOccurrences(of: "[", with: "")
let componentsString = componentsStringStepOne.replacingOccurrences(of: "]", with: "")
let components = componentsString.components(separatedBy: ", ")
return UIColor(red: CGFloat((components[0] as NSString).floatValue), green: CGFloat((components[1] as NSString).floatValue), blue: CGFloat((components[2] as NSString).floatValue), alpha: CGFloat((components[3] as NSString).floatValue))
}
}
还有没有更好的方法来编写这部分代码?
let componentsStringStepOne = string.replacingOccurrences(of: "[", with: "")
let componentsString = componentsStringStepOne.replacingOccurrences(of: "]", with: "")
let components = componentsString.components(separatedBy: ", ")
感谢任何帮助!谢谢。
【问题讨论】:
-
黑色只有 2 个分量(白色和 alpha)。永远不要假设一种颜色具有特定数量的成分。有不同的颜色模型。白色(灰度)、RGBA、HSBA 等。查询
cgColor有多少组件。 -
感谢 rmaddy,这解释了错误的原因。