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
}
}
}
}
}
Swift 4.2: Saving and loading colours / colours to user defaults
note: the load from defaults works but contains a deprecated item which does not yet have a good worked example to replace it.
let colorToSetAsDefault : UIColor = view.backgroundColor!
do
{
let data : NSData = try NSKeyedArchiver.archivedData(withRootObject: colorToSetAsDefault,requiringSecureCoding: false) as NSData
UserDefaults.standard.set(data, forKey: "userHeadingColor") // your key in quotes
UserDefaults.standard.synchronize()
} // end of do
catch
{
print("Couldn't save color")
} // end of catch
// load the color back as a test to make sure the save has worked
if let colorObject = UserDefaults.standard.object(forKey: "userHeadingColor")
{
let colorData = colorObject as! NSData
let color = NSKeyedUnarchiver.unarchiveObject(with: colorData as Data) as? UIColor
// replace with unarchivedObjectOfClass:fromData:error:
self.testDefaultsView.backgroundColor = color
}
else
{
}