与小部件 iOS14 内的项目交互

问题描述

我正在尝试像在 YouTube Music 中一样创建一个中等大小的 Widget,但我不明白如何在 Widget 中创建与特定项目的交互。当用户按下第一个或第二个项目时,我的应用程序应该如何理解,然后我必须如何在应用程序内部处理此操作。我的应用程序使用 Swift 而不是 SwiftUI,仅用于我使用 SwiftUI 的小部件。过去我没有使用 SwityUI 的经验。

我的 Widget 代码

colors = [ '#99f3bd','#fbaccc','#a8df65','#ff7b54']
fig,ax = plt.subplots(figsize=(5,15))
ax.set_title('Treatment Group',fontsize=25,fontname="Times New Roman Bold")
ax = df['q6_t'].value_counts(normalize=True).plot.pie(autopct='%1.0f%%',colors = colors)
ax.set_ylabel("")
plt.savefig('q6_t.png',bBox_inches = 'tight',transparent=True) 

解决方法

您可以使用 SwiftUI 中的链接来完成此操作。

Link(destination: url,label: {
  // add your UI components in this block on which you want to perform click action.
}

url:提供一个唯一的字符串来标识主应用程序中的小部件操作。

现在在主应用程序中,在 AppDelegate.swift 文件中使用以下方法:

func application(_ app: UIApplication,open url: URL,options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
}

在此方法中,您可以识别来自 WidgetKit 操作的 URL。