Deep_Dev
article thumbnail

 

📚 Save Color in UserDefaults from Color Picker 

 

 

 

variable in Color Data 

private let COLOR_KEY = "COLOR"
private let userDefaults = UserDefaults.standard

 

saveColor

func saveColor(color: Color) {
        let color = UIColor(color).cgColor
        
        if let components = color.components {
            userDefaults.set(components, forKey: COLOR_KEY)
        }
    }

 

loadColor

func loadColor() -> Color {
        guard let colorComponenets = userDefaults.object(forKey: COLOR_KEY) as? [CGFloat] else {
            return Color.purple
        }
        
        let color = Color(.sRGB,
                          red: colorComponenets[0],
                          green:colorComponenets[1],
                          blue:colorComponenets[2],
                          opacity: colorComponenets[3]
        )
        return color
    }

 

 

ColorData 전체 코드

View

struct ContentView: View {
    @State private var color = Color.purple
    private var colorData = ColorData()
    
    var body: some View {
        VStack {
            Circle()
                .frame(height:400)
                .foregroundColor(color)
                .padding()
            ColorPicker("Select a Color", selection: $color)
            Button("Save Color") {
                colorData.saveColor(color: color)
            }
            Spacer()
        }
        .onAppear(perform: {
            color = colorData.loadColor()
        })
        .padding()
    }
}

 

 

Result

 

 

 

 

 

 

 

 

'🍎 iOS > SwiftUI' 카테고리의 다른 글

[SwiftUI] Property Wrapper ②  (3) 2024.03.27
[SwiftUI] 프로퍼티래퍼 정리  (0) 2024.03.17
[iOS][SwiftUI] @State @Binding  (1) 2024.01.07
[iOS][SwiftUI] @main @UIApplicationMain  (0) 2023.12.28
[iOS][SwiftUI] Init ()  (0) 2023.12.28