Reputation: 7212
I know I can change the views background colors in SwiftUI with this code:
.background(Color(.systemGroupedBackground))
But I can't do it for widget background color itself!
I use this code:
struct XWidget: Widget { // MARK: Widget is defined here
var body: some WidgetConfiguration {
StaticConfiguration(
kind: "xWidget",
provider: xProvider(),
placeholder: Text("Loading...")) { entry in
xWidgetEntryView(entry: entry).background(Color(.systemGroupedBackground)) // <= here
}.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
}
}
But the result is like this:
Upvotes: 17
Views: 14408
Reputation: 1674
In iOS 17+, containerBackground(_:for:) is available.
public var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: MyCustomTimeline()) { entry in
MyCustomWidgetView(entry: entry)
.containerBackground(.red.tertiary, for: .widget)
}
}
Upvotes: 9
Reputation: 257693
You need to specify full frame, as on below demo
StaticConfiguration(
kind: "xWidget",
provider: xProvider(),
placeholder: Text("Loading...")) { entry in
xWidgetEntryView(entry: entry)
.frame(maxWidth: .infinity, maxHeight: .infinity) // << here !!
.background(Color.green)
}.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
Upvotes: 43
Reputation: 2863
For those who are trying to change the widget background that supports both dark and light modes.
Assets.xcassets
in your Widget Extension"WidgetBackground"
"WidgetBackground"
"Any, Dark"
.background(Color("WidgetBackground"))
public var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: MyCustomTimeline()) { entry in
MyCustomWidgetView(entry: entry)
.background(Color("WidgetBackground"))
}
}
Upvotes: 22
Reputation: 500
You can also set a color within your widget view using a ZStack like so:
var body: some View {
VStack {
ZStack {
Color.black
.ignoresSafeArea()
Link(destination: Deeplink.image.url!) {
Image("exampleImage")
.resizable()
.aspectRatio(contentMode: .fit)
.padding(.vertical, 3)
}
}
Text("Example text")
}
}
Upvotes: 6
Reputation: 1486
If you want to change the background color of your widget, you should modify your Assets.xcassets.
The Assets.xcassets in the Widget target has a Color Set named "WidgetBackground".
Changing the "WidgetBackground" color not only changes the background color of your widget, but also the background color of the add button of the widget that appears in the Widget Library.
Upvotes: 6