Tru*_*an1 1 ios appdelegate swift swiftui ios14
在我的 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
Run Code Online (Sandbox Code Playgroud)
但是,我在文档中注意到您可以制作UIApplicationDelegateAdaptor一个ObservableObject然后它将它注入到EnvironmentObject:
...delegate 将被放置在 Environment 中,并且可以通过使用
@EnvironmentObject视图层次结构中的属性包装器来访问。
我找不到任何有关如何工作的示例。使这项工作作为一个的语法是ObservableObject什么?
这是一个使用演示
AppDelegate到ObservableObjectclass 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
}
}
Run Code Online (Sandbox Code Playgroud)
AppDelegate像您一样将您注册为适配器@main
struct Testing_SwiftUI2App: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
// ... other code
Run Code Online (Sandbox Code Playgroud)
@EnvironmentObject在你的一些观点中声明,在需要的地方struct ContentView: View {
@EnvironmentObject var appDelegate: AppDelegate // << inject
var body: some View {
Text("Value: \(appDelegate.value)") // << use
}
}
Run Code Online (Sandbox Code Playgroud)
使用 Xcode 12 / iOS 14 测试。
| 归档时间: |
|
| 查看次数: |
914 次 |
| 最近记录: |