iOS 14 Widgets: How to create different layouts for every widget size family?

Viewed 6921

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?

2 Answers

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.

Related