For my widget, I want users to be able to select a widget background color of their choice, but I can't seem to get it to work.
I'm trying to do this with a ColorPicker and @AppStorage
ColorPicker("Background Color", selection: Binding(get: {
bgColor
}, set: { newValue in
backgroundColor = self.updateColorInAppStorage(color: newValue)
bgColor = newValue
}))
.frame(width: 200, height: 50)
.font(.headline)
backgroundColor is an @AppStorage variable that holds the RGB values
In my Widget extension class, I am using this variable to set the widget background color in the @main struct:
@main
struct MyWidget: Widget {
@AppStorage("backgroundColor", store: UserDefaults(suiteName: "group.com.MyWidget")) var backgroundColor = ""
@State private var bgColor = Color(UIColor.systemBackground)
let kind: String = "Count"
var body: some WidgetConfiguration {
IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in
SubscriberCountEntryView(entry: entry)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(bgColor)
.onAppear {
if (backgroundColor != "") {
let rgbArray = backgroundColor.components(separatedBy: ",")
if let red = Double(rgbArray[0]), let green = Double(rgbArray[1]), let blue = Double(rgbArray[2]), let alpha = Double(rgbArray[3]) {
bgColor = Color(.sRGB, red: red, green: green, blue: blue, opacity: alpha)
}
}
}
}
.configurationDisplayName("Count")
.supportedFamilies([.systemSmall, .systemMedium])
}
}
This only seems to be working when the app is first installed on the device. After that, no matter how many times I choose a color and update the widget, the background color won't change. If I delete and install the app again, the color changes.
Any ideas on how to do this properly?
