如何确认AppDelegate的ObservableObject?

时间:2020-07-20 15:23:24

标签: macos swiftui combine

我试图在macOS AppDelegate中观察一个值,但出现错误

ContentView.swift:14:6:通用结构“ ObservedObject”要求“ NSApplicationDelegate?”符合“ ObservableObject”

当我尝试使用ObservedObject将对象投射到as! ObservedObject中时,我遇到另一个错误

ContentView.swift:14:6:通用结构“ ObservedObject”要求“ ObservedObject”符合“ ObservableObject”

内部AppDelegate.swift文件

import Cocoa
import SwiftUI
import Combine

@NSApplicationMain
class AppDelegate: NSObject, ObservableObject, NSApplicationDelegate  {
    var isFocused = true
    
    // Other code app life-cycle functions
}

ContentView.swift文件内部

import SwiftUI
import Combine

struct ContentView: View {
    @ObservedObject var appDelegate = NSApplication.shared.delegate
    
    // Other UI code
}

1 个答案:

答案 0 :(得分:1)

这看起来像是概念的混合。.我建议避免这种情况……而是创建显式的可观察类。

像下面一样(抓痒)

class AppState: ObservableObject {
  @Published var isFocused = true
}

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate  {
    var appState = AppState()
    
    // Other code app life-cycle functions

     // in place where ContentView is created
     ...
     ContentView().environmentObject(self.appState)
     ...
}

在ContentView中只需使用它

struct ContentView: View {
    @EnvironmentObject var appState: AppState
    
    // Other UI code

    var body: some View {
       // .. use self.appState.isFocused where needed
    }
}