I want to create different layouts for each widget size (i.e. small, medium, large). How can I branch my code according to widget's size?
From the Home Screen, touch and hold a widget or an empty area until the apps jiggle. in the top left-hand corner. Select a widget, choose from the three different widget sizes, then tap Add Widget. Tap Done.
Here's how to create custom widgets on your iPhone. iOS 14 and higher lets you put widgets on your iPhone home screen. And thanks to third-party apps, you can actually create your own widgets. Not only do you get new functionality on your home screen, but you can also create it in your own unique style.
The WidgetFamily
(Apple Documentation) enum as part of WidgetKit
will allow you to switch upon the various sizes within your view and adjust accordingly. Set this as an @Environment
variable and switch on the avaliable cases:
.systemSmall
.systemMedium
.systemLarge
struct WidgetView : View {
@Environment(\.widgetFamily) var family
@ViewBuilder
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.")
}
}
}
Additionally to the accepted answer, in your Provider class methods (getTimeline, getSnapshot & placeholder) you get a context object which has a family member var.
family can be one of the three widget sizes: .systemSmall, .systemMedium & .systemLarge
Apple's official documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With