如何从 NSViewRepresentable/UIViewRepresentable 的协调器类中访问环境对象?



我得到了一个名为appState的EnvironmentObject,它可以通过我的一些视图访问以共享数据/状态。我在视图中使用它们的方式如下:

struct MetalView: NSViewRepresentable {
@EnvironmentObject var appState: AppState

如何从视图的Coordinator类访问appState

当我尝试以我尝试过的任何方式调用它时,我会得到以下错误:

类型为"MetalView"的实例成员"appState"不能用于嵌套类型为"MetalView.ACoordinator"的实例

以下是我解决这个问题的方法:

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/UIWiewRepresentable协调器类访问:

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)
}
...

最新更新