这是我解决这个问题的方法:
AppState.swift:
class AppState: ObservableObject {
static let shared = AppState()
init () {} // TODO: was private init, find out if this has benefits
@Published var currentView: String = "login"
// add rest of shared stuff below
AppDelegate.swift:
func applicationDidFinishLaunching(_ aNotification: Notification) {
let appState = AppState.shared
从 SwiftUI 视图访问:
struct ContentView: View {
@EnvironmentObject var appState: AppState
从 NSViewRepresentable / UIViewRepresentable Coordinator 类访问:
class Coordinator: NSObject, MTKViewDelegate {
...
func draw(in view: MTKView) {
...
context.render((AppState.shared.rawImage ?? AppState.shared.rawImageOriginal)!,
to: drawable.texture,
commandBuffer: commandBuffer,
bounds: AppState.shared.rawImageOriginal!.extent,
colorSpace: colorSpace)
}
...
这花了我很多时间来弄清楚,所以我希望它可以帮助一些初学者 SwiftUI 程序员......
如果高级程序员可以改进这一点,请这样做我可以从中学习。