gpt4 book ai didi

Swift - UIColor.black 在从 UIColor 转换为字符串时使应用程序崩溃

转载 作者:行者123 更新时间:2023-11-28 07:32:28 29 4
gpt4 key购买 nike

例如,下面的代码与 UIColor.Purple 或 UIColor.Yellow 一起工作正常,但当我使用 UIColor.black 时应用程序崩溃。

fatal error :索引超出范围使用 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: ", ")

感谢任何帮助!谢谢。

最佳答案

这是我在 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))
}
}
}

关于Swift - UIColor.black 在从 UIColor 转换为字符串时使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54301117/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com