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

r6hnlfcb  于 2023-03-17  发布在  Swift
关注(0)|答案(1)|浏览(136)

我得到了一个名为appState的EnvironmentObject,它通过我的一些视图来访问,以共享数据/状态。

struct MetalView: NSViewRepresentable {
@EnvironmentObject var appState: AppState

如何从视图的Coordinator类访问appState
当我尝试以任何方式调用它时,我得到这个错误:
类型“MetalView”的示例成员“appState”不能用于嵌套类型“MetalView.Coordinator”的示例

mzsu5hc0

mzsu5hc01#

下面是我解决这个问题的方法:
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协调器类访问:

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

相关问题