当小部件打开应用程序时,应用程序可以知道小部件的大小

When a widget opened an app, can the app knows the widget size

当点击 iOS 14 小部件时,它会打开应用程序:

var body: some View {
    Text(entry.text)
        .widgetURL(WidgetEntryView.deeplinkURL)
}

应用程序能否获取打开它的小部件的大小(小、中、大)?

您可以使用 @Environment(\.widgetFamily) 并将其传递给 widgetURLLink:

struct Widget1EntryView: View {
    @Environment(\.widgetFamily) var widgetFamily

    var entry: Provider.Entry

    var deeplinkURL: URL {
        URL(string: "widget-deeplink://widgetFamily/\(widgetFamily)")!
    }

    var body: some View {
        VStack {
            Link("Tap me", destination: deeplinkURL)
            Text("Widget family: \(String(describing: widgetFamily))")
                .widgetURL(deeplinkURL)
        }
    }
}

然后检测在你的主应用中打开这个URL:

struct ContentView: View {
    var body: some View {
        Text("Test")
            .onOpenURL { url in
                print(url) // prints `widget-deeplink://widgetFamily/systemSmall`
                print(url.lastPathComponent) // prints `systemSmall`
            }
    }
}

这里有一个 GitHub repository 包含不同的 Widget 示例,包括 DeepLink 和 Environment Widgets。