79197451

Date: 2024-11-17 15:02:36
Score: 0.5
Natty:
Report link

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
                }
            }
        }
    }
}
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @AppStorageUsage
  • Low reputation (1):
Posted by: K.pen