提问人:Saeed Noshadi 提问时间:9/16/2022 更新时间:9/19/2022 访问量:763
如何在 SwiftUi 的@AppStorage中保存颜色
How to save a Color in the @AppStorage in SwiftUi
问:
我想在@AppStorage中保存 Color 值,但出现错误。我该如何解决?
@AppStorage ("selectedColor") var selectedColor: Color = .teal
答:
4赞
dibs
9/19/2022
#1
将颜色另存为字符串
@AppStorage ("selectedColor") var selectedColor: String = ""
创建一个将颜色转换为字符串的函数
func updateCardColorInAppStorage(color: Color)-> String {
let uiColor = UIColor(color)
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
uiColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return "\(red),\(green),\(blue),\(alpha)"
}
和字符串到颜色
if (cardColor != "" ) {
let rgbArray = cardColor.components(separatedBy: ",")
if let red = Double (rgbArray[0]), let green = Double (rgbArray[1]), let blue = Double(rgbArray[2]), let alpha = Double (rgbArray[3]){ bgColor = Color(.sRGB, red: red, green: green, blue: blue, opacity: alpha)
}
评论