Skip to content

Instantly share code, notes, and snippets.

@mayoff
Last active August 23, 2021 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayoff/a571383a31f9c21df08b74e5a2969109 to your computer and use it in GitHub Desktop.
Save mayoff/a571383a31f9c21df08b74e5a2969109 to your computer and use it in GitHub Desktop.
defining an extra-large widget only if on iOS 15

You probably have a WidgetBundle type in your widget extension like this:

@main
struct MyWidgets: WidgetBundle {
    var body: some Widget {
        SmallWidget()
        MediumWidget()
        LargeWidget()
    }
}

Instead of defining one WidgetBundle annotated @main, define two WidgetBundles (one with the extra-large widget, the other without), and do not annotate either one @main.

Define your own non-WidgetBundle type with a static func main and annotate your type @main.

In your static func main, call the main of the appropriate WidgetBundle type depending on whether you're on iOS 15.

struct MyWidgets_14: WidgetBundle {
    var body: some Widget {
        SmallWidget()
        MediumWidget()
        LargeWidget()
    }
}

@available(iOS 15, *)
struct MyWidgets_15: WidgetBundle {
    var body: some Widget {
        SmallWidget()
        MediumWidget()
        LargeWidget()
        ExtraLargeWidget()
    }
}

@main
struct WidgetExtMain {
    static func main() {
        if #available(iOS 15, *) {
            MyWidgets_15.main()
        } else {
            MyWidgets_14.main()
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment