Widget 的 Container Background

Widget 的 Container Background

温馨提示:本文最后更新于2025-01-10 12:13:13,某些文章具有时效性,若有错误或已失效,请在下方留言

Widget Container Background(容器背景) 是在 iOS 17 中引入的。在 Widget 的开发过程中,可能会在预览中遇到如下的错误

Widget needs to adopt container background.

容器背景用途

iOS 17 引入 Container Background, 允许开发人员定义 Widget 的背景视图,使系统更容易适应不同的上下文。

widget 显示在主屏幕上的时候,背景将会可见,处于待机状态时,背景会自动删除。

主屏幕显示与待机现实
主屏幕显示与待机现实

禁用容器背景

使用containerBackgroundRemovable() 修饰符即可

struct Dex3Widget: Widget {
    // widget唯一标识符
    let kind: String = "Dex3Widget"

    var body: some WidgetConfiguration {
        // StaticConfiguration,静态widget,没有开启IntentConfiguration,不需要动态更新的小组件
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            if #available(iOS 17.0, *) {
                // 添加 Dex3WidgetEntryView 为 widget 的视图
                Dex3WidgetEntryView(entry: entry)
                    .containerBackground(.fill.tertiary, for: .widget)

            } else {
                // 添加 Dex3WidgetEntryView 为 widget 的视图
                Dex3WidgetEntryView(entry: entry)
                    .background()
            }
        }
        // 设定当前widget支持的尺寸,可以设置小中大三种
        .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
        // 显示在小组件库中的名字
        .configurationDisplayName("My Widget")
        // 显示在小组件库中的描述
        .description("This is an example widget.")
        // 禁用背景视图的删除
        .containerBackgroundRemovable(false)
        // 移除多余的 Margin
        .contentMarginsDisabled()
    }
}

删除多余 Margin

.contentMarginsDisabled() 修饰符,可以删除 Widget 中多余的 Margin

删除多余 Margin
删除多余 Margin

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容