简体   繁体   English

在 SwiftUI 生命周期中投射 AppDelegate

[英]Cast AppDelegate in SwiftUI Lifecycle

How do you do the cast below, in an App with SwiftUI Lifecycle, where AppDelegate is implemented as NSApplicationDelegateAdaptor ?您如何在具有 SwiftUI 生命周期的应用程序中进行以下转换,其中 AppDelegate 被实现为NSApplicationDelegateAdaptor

let appDelegate = NSApplication.shared.delegate as! AppDelegate

// or
let appDelegate = NSApp.delegate as! AppDelegate

The above throws the following error:上面抛出以下错误:

Could not cast value of type 'SwiftUI.AppDelegate' (0x1e28fae40) to 'MyApp.AppDelegate' (0x102d277c0).无法将“SwiftUI.AppDelegate”(0x1e28fae40)类型的值转换为“MyApp.AppDelegate”(0x102d277c0)。

Background is using AppDelegate in an Extension背景在扩展中使用 AppDelegate

extension NSStatusBarButton {
    public override func mouseDown(with event: NSEvent) {
        super.mouseDown(with: event)
        let appDelegate = NSApp.delegate as! AppDelegate
        // do stuff with appDelegate on MouseDown Event
    }
}

We must not cast, because NSApp's delegate is not our delegate, but internal, which redirects some callbacks to that one injected via adapter.我们不能强制转换,因为 NSApp 的委托不是我们的委托,而是内部的,它将一些回调重定向到通过适配器注入的回调。

We can access our delegate directly via variable of adapter:我们可以通过适配器的变量直接访问我们的委托:

@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

or via EnvironmentObject (for that AppDelegate have confirm to ObservableObject protocol), which is injected into ContentView for us automatically and so available inside all subviews:或通过EnvironmentObject (因为AppDelegate已确认ObservableObject协议),它会自动为我们注入到ContentView中,因此在所有子视图中可用:

struct MyView: View {
  @EnvironmentObject var appDelegate: AppDelegate

  // ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM