在Xcode预览时,发现如下报错:
[Remote] WidgetBackgroundAbsentError: Get ready to preview in this file
Ensure that you have called the `containerBackground(for: .widget) {…}` modifier in your widget view.
Read more in [Developer Documentation](https://developer.apple.com/documentation/widgetkit/preparing-widgets-for-additional-contexts-and-appearances).
这是WidgetKit的预览报错,表示正在预览一个Widget,但是根视图没有调用containerBackground(for: .widget) 修饰器。
这是 Xcode 15 / iOS 17 之后的 WidgetKit 新要求:
Widget 的顶层视图必须声明它支持在不同上下文(例如主屏幕、锁屏、Smart Stack)中渲染的背景。
问题代码:
struct PlaceholderWidget: Widget {
let kind: String = "PlaceholderWidget"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: BankletWidgetProvider()) { entry in
PlaceholderView(entry: entry)
}
.configurationDisplayName("Featured Images")
.description("This is an example widget.")
.supportedFamilies([.systemSmall])
}
}
解决方案,在根视图上添加 .containerBackground(for: .widget):
StaticConfiguration(kind: kind, provider: BankletWidgetProvider()) { entry in
PlaceholderView(entry: entry)
.containerBackground(.clear, for: .widget) // 添加该行代码
}
.containerBackground(for: .widget) 的作用是,WidgetKit 由开发者或者系统提供背景。
这里用 .containerBackground(for: .widget) { Color.clear } 就是声明不需要系统提供背景。