I am out of ideas. I am trying to have a color theme picker in a view that would allow selection of predefined color theme values, store it in SwiftData as persistent storage and then use it throughout the app.
I have this model to store values for Red Green and Blue:
import Foundation
import SwiftUI
import SwiftData
@Model
class SettingsModel {
var red: CGFloat
var green: CGFloat
var blue: CGFloat
init(red: CGFloat, green: CGFloat, blue: CGFloat) {
self.red = red
self.green = green
self.blue = blue
}
}
I reference it in my App root view:
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: SettingsModel.self)
}
In the actual view I define an array of color themes with custom RGB values that can be selected in the Picker. In the onChange of the Picker I can see the actual color values with color.red, color.green, color.blue but when I want to see what is inside the model with the List then they are all 0:
import SwiftUI
import SwiftData
struct SettingsView: View {
@Environment(.modelContext) var context
@Query private var colorTheme: [SettingsModel]
@State private var selectedColor: String = "Theme 1"
struct RGBColor {
let red: CGFloat
let green: CGFloat
let blue: CGFloat
}
let colorThemes: [String: RGBColor] = [
"Theme 1": RGBColor(red: 0, green: 199, blue: 190),
"Theme 2": RGBColor(red: 50, green: 173, blue: 230),
"Theme 3": RGBColor(red: 88, green: 86, blue: 214),
]
var body: some View {
VStack {
Picker("Color Theme", selection: $selectedColor) {
ForEach(Array(colorThemes.keys), id: .self) { name in
Text(name).tag(name)
}
}
.onChange(of: selectedColor) {
if let color = colorThemes[selectedColor] {
context.insert(SettingsModel(red: color.red, green: color.green, blue:
color.blue))
}
}
List(colorTheme) { color in
Text("R: (String(format: "%.2f", color.red)), G: (String(format: "%.2f",
color.green)), B: (String(format: "%.2f", color.blue))")
}
}
}
}
I am not getting any errors, just 0 data in the store after context.insert().
5