swiftswiftuiappkitmetalkit

How can I access an EnvironmentObject from within a NSViewRepresentable/UIViewRepresentable's Coordinator class?


I got an EnvironmentObject named appState, which is accessed through some of my views to share data/states. The way I use them in a view is like this:

struct MetalView: NSViewRepresentable {
@EnvironmentObject var appState: AppState

How can I access appState from my view's Coordinator class?

When I try to call it in any way I've tried yet, I get this error:

Instance member 'appState' of type 'MetalView' cannot be used on instance of nested type 'MetalView.Coordinator'


Solution

  • Here is how I solved this:

    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
    

    Access from SwiftUI Views:

    struct ContentView: View {
        @EnvironmentObject var appState: AppState
    

    Access from NSViewRepresentable / UIViewRepresentable Coordinator Class:

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