Save Color

PHOTO EMBED

Fri Aug 04 2023 13:13:30 GMT+0000 (Coordinated Universal Time)

Saved by @zelda #swift #swiftui

import SwiftUI

struct ContentView: View {
    private let userDefaults = UserDefaults.standard
    private let COLOR_KEY = "COLOR_KEY"
    @State var selectedColor: Color = .purple
    
    var body: some View {
        NavigationView {
            VStack(spacing: 20) {
                RoundedRectangle(cornerRadius: 20)
                    .fill(selectedColor)
                    .frame(height: 240)
                    .overlay {
                        Text("Red")
                            .font(.system(.title))
                            .foregroundColor(.white)
                    }
                
                Button {
                    saveColor(color: selectedColor)
                } label: {
                    Text("Save Color")
                        .frame(maxWidth: .infinity)
                        .font(.system(.headline, design: .rounded))
                }
                .padding()
                .frame(maxWidth: .infinity)
                .foregroundColor(.white)
                .background(selectedColor)
                .cornerRadius(10)
                
                Spacer()
            }
            .padding()
            .navigationBarTitle("Save Color", displayMode: .inline)
            .navigationBarItems(trailing: ColorPicker("", selection: $selectedColor))
            .onAppear {
                selectedColor = loadColor()
            }
        }
    }
    
    // Save Color
    func saveColor(color: Color) {
        let color = UIColor(color).cgColor
        
        if let components = color.components {
            userDefaults.set(components, forKey: COLOR_KEY)
            print("Save Color: \(components)")
        }
    }
    
    // Load Color
    func loadColor() -> Color {
        guard let array = userDefaults.object(forKey: COLOR_KEY) as? [CGFloat] else {
            return Color.purple
        }
        print("Load Color: \(array)")
        
        let color = Color(.sRGB, red: array[0], green: array[1], blue: array[2], opacity: array[3])
        return color
    }
}
content_copyCOPY