如何检测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环境变量来区分场景:
- 在小组件视图中添加环境属性,获取当前渲染模式:
@Environment(\.widgetRenderingMode) private var renderingMode
- 根据
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
相关产品推荐
相关产品推荐

