如何确认 AppDelegate 的 ObservableObject?
Posted
技术标签:
【中文标题】如何确认 AppDelegate 的 ObservableObject?【英文标题】:How to confirm ObservableObject for an AppDelegate? 【发布时间】:2020-07-20 15:23:24 【问题描述】:我正在尝试观察 macOS AppDelegate 中的值,但出现错误
ContentView.swift:14:6:通用结构“ObservedObject”需要“NSApplicationDelegate?”符合'ObservableObject'
当我尝试使用as! ObservedObject
将对象转换为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】:这看起来像是概念的混合......我建议避免这样......而是创建显式可观察类。
如下图(略)
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
【讨论】:
以上是关于如何确认 AppDelegate 的 ObservableObject?的主要内容,如果未能解决你的问题,请参考以下文章
如何从 AppDelegate 访问 ViewController 变量
如何从 AppDelegate.m 访问 tabBarController?