Use hex strings for simplicity when saving colors with @AppStorage
extension Color {
func toData() -> Data? {
try? NSKeyedArchiver.archivedData(withRootObject: UIColor(self), requiringSecureCoding: false)
}
static func fromData(_ data: Data) -> Color? {
if let uiColor = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? UIColor {
return Color(uiColor)
}
return nil
}
}
Usage
struct ContentView: View {
@State private var themeColor: Color = .white
var body: some View {
VStack {
Text("Hello, World!")
.padding()
.background(themeColor)
Button("Change Color") {
// Save color
if let colorData = Color.red.toData() {
UserDefaults.standard.set(colorData, forKey: "themeColor")
}
themeColor = .red
}
.onAppear {
// Retrieve color
if let colorData = UserDefaults.standard.data(forKey: "themeColor"),
let savedColor = Color.fromData(colorData) {
themeColor = savedColor
}
}
}
}
}