The widgetFamily
environment key is not setup in the app for obvious reasons, but you can implement it yourself.
First you need to make WidgetFamily
conform to EnvironmentKey
like this:
extension WidgetFamily: EnvironmentKey {
public static var defaultValue: WidgetFamily = .systemMedium
}
Then you need to add your custom environment key, like this:
extension EnvironmentValues {
var widgetFamily: WidgetFamily {
get { self[WidgetFamily.self] }
set { self[WidgetFamily.self] = newValue }
}
}
Now you can use the .environment()
modifier in the app:
struct ContentView: View {
var body: some View {
InterestingWidgetEntryView(entry: .init(date: .init()))
.environment(\.widgetFamily, .systemSmall)
}
}
This is how I created my widget view:
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.")
}
}
}
And this is the result:

Keep in mind that the widget view will not have the widget size, you'll have to calculate that yourself.