简体   繁体   中英

SwiftUI iOS14 Widget - Create create multi layout with the same WidgetFamily

When I add widgets from home screens, I can see that the Clock application created by Apple has two small WidgetFamily layouts.

How to make two small Widgets like in the Clock application?

I see that I only can create one layout for every WidgetFamily .

It seems that you need to create separate Widgets with their own view, entry, provider...

Here is a possible solution using WidgetBundle :

  1. Create separate Widgets (make sure the @main annotation is not attached to any of them):
struct Widget1: Widget {
    let kind: String = "Widget1"

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Widget1Provider()) { entry in
            Widget1Entry(entry: entry)
        }
        .configurationDisplayName("Widget1")
        .description("This is an example widget v1.")
    }
}

struct Widget2: Widget {
    let kind: String = "Widget2"

    var body: some WidgetConfiguration {
        ...
    }
}

...
  1. For each Widget create its own View (possibly also separate Entries and Providers, depending on what you need):
struct Widget1EntryView: View {
    var entry: Widget1Entry

    var body: some View {
        Text("Widget1")
    }
}

struct Widget2EntryView: View {
    var entry: Widget2Entry

    var body: some View {
        Text("Widget2")
    }
}

...
  1. Use WidgetBundle to provide a bundle containing your Widgets:
@main
struct WidgetsBudle: WidgetBundle {
    var body: some Widget {
        Widget1()
        Widget2()
        // add more Widgets if you want
    }
}

Note that @main is attached to WidgetsBudle and not to Widgets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM