如何确认 AppDelegate 的 ObservableObject?
How to confirm ObservableObject for an AppDelegate?
我试图在 macOS AppDelegate 中观察一个值,但出现错误
ContentView.swift:14:6: Generic struct 'ObservedObject' requires that 'NSApplicationDelegate?' conform to 'ObservableObject'
当我尝试使用 as! ObservedObject
将对象转换为 ObservedObject
时,出现另一个错误
ContentView.swift:14:6: Generic struct 'ObservedObject' requires that 'ObservedObject' conform to '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
}
这看起来像是概念的混合。我建议避免这样...而是创建显式可观察对象 class。
如下图(草图)
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
}
}
我试图在 macOS AppDelegate 中观察一个值,但出现错误
ContentView.swift:14:6: Generic struct 'ObservedObject' requires that 'NSApplicationDelegate?' conform to 'ObservableObject'
当我尝试使用 as! ObservedObject
将对象转换为 ObservedObject
时,出现另一个错误
ContentView.swift:14:6: Generic struct 'ObservedObject' requires that 'ObservedObject' conform to '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
}
这看起来像是概念的混合。我建议避免这样...而是创建显式可观察对象 class。
如下图(草图)
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
}
}