Fail to preview Widget in Xcode with SwiftUI Preview

9.3k views Asked by At

I am trying to preview some View by using Widget context, like:

struct MyTasksView_Previews: PreviewProvider {
    static var previews: some View {
            MyTasksView(
                myTasks: Fake.myTasks,
                user: Fake.user,
                error: ""
            )
            .previewContext(WidgetPreviewContext(family: .systemMedium))
    }
}

However, I'm getting this error while attempt to run the preview. And, I'm not sure why it is happing.

RemoteHumanReadableError: Unknown preview provider “MyTasksView_Previews” MyApp does not contain a preview provider named “MyTasksView_Previews”. Check your build settings to ensure the preview provider is compiled into your product.

I, also, tried to use a simple Text(text).previewContext(WidgetPreviewContext(family: .systemMedium)), but it did not work either. I'm using the Xcode beta 5.

In Apple Emoji Rangers Demo App for WWDC 2020. We can see this piece of code for preview:

struct CharacterNameView_Previews: PreviewProvider {
    static var previews: some View {
        CharacterNameView(CharacterDetail.panda)
            .previewContext(WidgetPreviewContext(family: .systemSmall))
    }
}

Emoji Rangers example

4

There are 4 answers

2
Isomiddin On

Add Widget extension target, and activate it. For more information https://developer.apple.com/documentation/widgetkit/creating-a-widget-extension

0
LeoNard On

I had the same problem when adding widgets extension to my UIKit app.

Changing the Class target membership to widget extension solved this for me.

2
alfred zh On

It's a bug in Xcode, you can only use previewContext of "single" Widgets Target. So you need to unselect other Targets.

enter image description here

0
Rufat Mirza On

I had the similar issue and I solved it by putting the View inside a VStack (or another container).

Here is my code that worked:

struct WidgetViewPreviews: PreviewProvider {

  static var previews: some View {
    VStack {
      WidgetView(entry: .mock)
    }
    .previewContext(WidgetPreviewContext(family: .systemSmall))
  }
}