无法更改 iOS14 小部件背景颜色

Can't change the iOS14 widget background color

我知道我可以使用以下代码更改 SwiftUI 中的视图背景颜色:

.background(Color(.systemGroupedBackground))

但是我不能为小部件背景颜色本身做这件事!

我使用这个代码:

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])
    }
}

但是结果是这样的:

需要指定全帧,如下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])

backup

如果你想改变你的小部件的背景颜色,你应该修改你的Assets.xcassets。

Widget 目标中的 Assets.xcassets 有一个名为“WidgetBackground”的颜色集。

更改“WidgetBackground”颜色不仅会更改您的 widget 的背景颜色,还会更改出现在 Widget Library 中的 widget 添加按钮的背景颜色。

您还可以使用 ZStack 在小部件视图中设置颜色,如下所示:

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")
        }
    }

对于那些试图更改同时支持 darklight 模式的小部件背景的人。

更改小部件背景颜色(支持深色模式)

  1. 转到 小部件扩展程序中的 Assets.xcassets
  2. 应该有一个 颜色集 已经有了名字 "WidgetBackground"
  3. 如果缺少,则创建一个新的颜色集并将其命名为"WidgetBackground"
  4. 转到 Attribute Inspector 并确保 Appearances 设置为 "Any, Dark"

  1. 转到 Widget ExtensionBuild Settings 并搜索 Asset Catalog Compiler - Options
  2. 确保小部件背景颜色名称设置为颜色集“WidgetBackground”的名称

  1. 转到您的小部件视图并设置其背景颜色.background(Color("WidgetBackground"))
public var body: some WidgetConfiguration {
    StaticConfiguration(kind: kind, provider: MyCustomTimeline()) { entry in
        MyCustomWidgetView(entry: entry)
            .background(Color("WidgetBackground"))
    }
}
  1. 在设备(或模拟器)上编译和 运行 并检查当前外观的颜色更新