You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测watchOS上.accessoryRectangular小组件的显示位置?

如何检测watchOS小组件的显示位置(适配.accessoryRectangular类型)

我创建了适配.accessoryRectangular类型的watchOS小组件,它会在两个场景显示:表盘界面,以及watchOS 10的底部面板。我需要根据显示位置展示不同内容——在底部面板时只显示图片,表盘界面显示文本+图片,请问怎么检测组件当前的显示位置?

当前我的代码实现如下:

if family.isRectangular {
    ZStack(alignment: Alignment(horizontal: .leading, vertical: .top)) {
        Image.network
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 15, height: 18)
        Text(verbatim: "      \(entry.title ?? \"\"")")
            .font(Font.openSansRegular(withSize: 14))
            .multilineTextAlignment(.leading)
    }
}

解决方案

要检测.accessoryRectangular组件的显示位置,可通过读取WidgetRenderingMode环境变量来区分场景:

  1. 在小组件视图中添加环境属性,获取当前渲染模式:
@Environment(\.widgetRenderingMode) private var renderingMode
  1. 根据renderingMode的值判断显示场景:
    • .full:对应表盘界面的常规显示状态
    • .accessory:对应watchOS 10底部面板的显示状态

修改后的代码示例(已修正原代码的引号错误):

if family.isRectangular {
    ZStack(alignment: Alignment(horizontal: .leading, vertical: .top)) {
        Image.network
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 15, height: 18)
        
        // 仅在表盘界面(full模式)显示文本
        if renderingMode == .full {
            Text(verbatim: "      \(entry.title ?? "")")
                .font(Font.openSansRegular(withSize: 14))
                .multilineTextAlignment(.leading)
        }
    }
}

注意事项

  • 确保项目的watchOS目标版本不低于10.0,底部面板是该版本新增特性
  • WidgetRenderingMode还包含.accessoryInline等其他值,但对于.accessoryRectangular类型,只需区分.full和.accessory即可满足需求

内容的提问来源于stack exchange,提问作者kunass2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 09:40:09