swiftui - 不在小部件中时如何设置 .widgetFamily @Environment 变量?
问题描述
我想在我的主应用程序中预览我的 WidgetKit 小部件。
小部件的布局.systemSmall
和.systemMedium
大小不同。
当我.environment(\.widgetFamily, .systemSmall)
在主应用程序中设置时,出现构建错误:
Key path value type 'WritableKeyPath<EnvironmentValues, WidgetFamily>' cannot be converted to contextual type 'KeyPath<EnvironmentValues, WidgetFamily>'
如果我不设置值,则默认为.systemMedium
.
有没有办法使用.systemSmall
?
解决方案
由于widgetFamily
显而易见的原因,未在应用程序中设置环境密钥,但您可以自己实现它。
首先,您需要像这样WidgetFamily
符合EnvironmentKey
:
extension WidgetFamily: EnvironmentKey {
public static var defaultValue: WidgetFamily = .systemMedium
}
然后您需要添加您的自定义环境密钥,如下所示:
extension EnvironmentValues {
var widgetFamily: WidgetFamily {
get { self[WidgetFamily.self] }
set { self[WidgetFamily.self] = newValue }
}
}
现在您可以.environment()
在应用程序中使用修饰符:
struct ContentView: View {
var body: some View {
InterestingWidgetEntryView(entry: .init(date: .init()))
.environment(\.widgetFamily, .systemSmall)
}
}
这就是我创建小部件视图的方式:
struct InterestingWidgetEntryView : View {
@Environment(\.widgetFamily) var family
var entry: Provider.Entry
var body: some View {
switch family {
case .systemSmall:
Text("Small")
case .systemMedium:
Text("Medium")
case .systemLarge:
Text("Large")
default:
Text("Some other WidgetFamily in the future.")
}
}
}
这是结果:
请记住,小部件视图没有小部件大小,您必须自己计算。
推荐阅读
- azure - 如何检查哪个 Azure 资源正在使用特定的 IP 地址?
- botframework - 如何将 botbuilder 示例部署为 Azure Function
- reactjs - 如何使用三元运算符显示元素
- bash - 从路径名扩展结果中排除目录
- python - 更新烧瓶模型后无法插入或更新到新列数据库
- excel - 如何在不跳过列的情况下从合并单元格复制和粘贴公式
- python - 如何使我的矩形与旋转精灵一起旋转
- node.js - Giphy API 总是提供相同的 gif (discord.js)
- react-native - 我已经在 play 和 apple store 上发布了一个 expo 应用程序。在这种情况下,如何使用 OTA 无线更新?
- ios - 无法使用 React Native WebView 在 iOS 中单击和拨打电话号码