Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 747
Feridun Erbaş Avatar asked Aug 04 '20 12:08

Feridun Erbaş


People also ask

How do I get different sized widgets on my iPhone?

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.

Can you make custom widgets on iOS 14?

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.


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

    }
}
like image 120
Leon Storey Avatar answered Oct 05 '22 23:10

Leon Storey


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.

like image 32
Cosmin Avatar answered Oct 05 '22 23:10

Cosmin