在我的 iOS 14 中App
,我可以登记遗产AppDelegate
通过做这个:
@main
struct MyApp: App {
#if os(iOS)
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
#endif
var body: some Scene {
...
}
}
#if os(iOS)
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
SomeSDK.configure(with: launchOptions)
return true
}
}
#endif
然而,我注意到在文档你(们)能做到UIApplicationDelegateAdaptor
an ObservableObject
然后它会将其注入EnvironmentObject
:
...delegate 将被放置在环境中,并且可以通过使用@EnvironmentObject
视图层次结构中的属性包装器。
我找不到任何关于这是如何工作的例子。使其工作的语法是什么ObservableObject
?
这是一个使用演示
- Confirm
AppDelegate
to ObservableObject
class AppDelegate: NSObject, UIApplicationDelegate, ObservableObject {
@Published var value: String = ""
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
self.value = "test" // in any callback use your published property
return true
}
}
- 注册您的
AppDelegate
像你一样作为适配器
@main
struct Testing_SwiftUI2App: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
// ... other code
- Declare
@EnvironmentObject
在某些人看来,在需要的地方
struct ContentView: View {
@EnvironmentObject var appDelegate: AppDelegate // << inject
var body: some View {
Text("Value: \(appDelegate.value)") // << use
}
}
使用 Xcode 12 / iOS 14 进行测试。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)