【问题标题】:Swift - UIColor.black crashes app when converting from UIColor to stringSwift - 从 UIColor 转换为字符串时,UIColor.black 使应用程序崩溃
【发布时间】: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,这解释了错误的原因。

标签: swift uikit uicolor rgba


【解决方案1】:

这是我在 rmaddy 和 kamran 响应之后提出的解决方案。它没有使应用程序崩溃,而且我得到了正确的颜色。它在 plist 中保存了我希望它是黑色还是彩色的外观,例如。 [0.2,0.4,0.5,1.0]。 感谢您的帮助

public extension UIColor {

class func StringFromUIColor(color: UIColor) -> String{
    let components = color.cgColor.components
    if components?.count == 2 {
         return "[\(components![0]), \(components![0]), \(components![0]), \(components![1])]"
    } else {
        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: ", ")
    if components.count == 2 {
        return UIColor(white: CGFloat((components[0] as NSString).floatValue), alpha: CGFloat((components[1] as NSString).floatValue))
    } else {
          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))
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-29
    • 2020-04-21
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    相关资源
    最近更新 更多