Search code examples
iosswiftswiftuiios14widgetkit

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


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?


Solution

  • 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.")
            }
    
        }
    }