如何从小部件扩展导航到UIKit视图控制器



我目前正在尝试用SwiftUI制作一个小部件。假设我的代码是这样的:

struct WidgetView: View {
var data : DataProvider.Entry
var body: some View {
ZStack {
Image("Clicker")
.padding(.all, 15)
}.widgetURL(URL(string: "ClickerViewController"))
.padding(.all, 30)
.background(Color.green)
}
}

此时,点击小部件会打开应用程序的主屏幕。想要导航到特定屏幕。supportedFamilies:系统小型-因此需要使用小工具URL而不是。链接

那么,URL在哪里是Clicker,如何导航到名为ClickerViewController的viewController?如何处理这些链接?我想,在不久的将来,任何例子或解释都会对我和其他很多人有所帮助;(

谢谢!

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
}

当我点击小部件时,我在SceneDelegate中执行了这个方法。您可以处理您的url并重定向到ViewController

以下是的可能方法

var body: some Scene {
@StateObject private var appState = AppState()
WindowGroup {
ContentView()
.environmentObject(appState)
.onOpenURL(perform: { url in
appState.handle(url)       // redirect to app state
})
}
}

AppState可以具有例如

class AppState: ObservableObject {
@Published var appScreen: _SomeEnumType_
func handle(url: URL) {
// ... update `appScreen` here correnspondingly
}
}

因此,在ContentView中,您可以根据应用程序状态切换显示的视图。

最新更新