Widget Previews in Xcode 12

WWDC2020 was chock full of exciting announcements. One the new things Apple introduced was WidgetKit, which enables us to add multi-platform widgets to our apps. I find this quite exciting and a great fit for my app Solar Watch and started experimenting right away. Go ahead and watch the WWDC videos related to widgets.

WidgetKit is a great framework which comes with two catches:

  1. The widgets cannot be interactive. But can contain buttons which deep-link into different parts of your app.
  2. The widgets must be implemented in SwiftUI. Which is not bad per se but means more work if you would like to quickly build a widget extension for your existing app.

This is a great reason to learn SwiftUI, if there ever was one!

When I started experimenting with different widgets, I could not get the SwiftUI previews to work. It kept erroring out with PreviewAgentError: Statically rendering previews is not supported on iOS simulators.

This seems to be a bug in Xcode 12 beta 1 (FB7797517). I’m sure it will get fixed quickly but in the meantime here is a workaround that you can use to preview your Widgets:

static var previews: some View {
  return Group {
    MyWidget()
      .previewContext(WidgetPreviewContext(family: .systemSmall))
    MyWidget()      
      .previewContext(WidgetPreviewContext(family: .systemMedium))
    MyWidget()
      .previewContext(WidgetPreviewContext(family: .systemLarge))
  }
}

And here is how it looks like for the SolarWatch Widget I am working on:

This works pretty well but the downside is it only works for subclasses of Widget. Also you’ll have to switch back and forth between your widget class and the view that you are working on.

Feel free to reach out over Twitter if you’ve found another solution.