Saeed Noshadi
Saeed Noshadi

Reputation: 1269

How to save a Color in the @AppStorage in SwiftUi

I want to save a Color value in the @AppStorage but I get an error. How can I fix it?

    @AppStorage ("selectedColor") var selectedColor: Color = .teal

enter image description here

Upvotes: 3

Views: 1328

Answers (1)

dibs
dibs

Reputation: 287

save color as string

@AppStorage ("selectedColor") var selectedColor: String = ""

create a function that transforms the color into a 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)"
}

and String to Color

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)
}

Upvotes: 4

Related Questions