[英]How to update EnvironmentObject variable from Coordinator class?
[英]How can I access an EnvironmentObject from within a NSViewRepresentable / UIViewRepresentable 's Coordinator class?
我有一個名為 appState 的 EnvironmentObject,可以通過我的一些視圖訪問它以共享數據/狀態。 我在視圖中使用它們的方式是這樣的:
struct MetalView: NSViewRepresentable {
@EnvironmentObject var appState: AppState
如何從我的視圖的 Coordinator class 訪問 appState?
當我嘗試以我嘗試過的任何方式調用它時,我收到此錯誤:
“'MetalView' 類型的實例成員 'appState' 不能用於嵌套類型 'MetalView.Coordinator' 的實例”
有什么線索嗎?
這是我解決這個問題的方法:
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 訪問:
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 程序員......
如果高級程序員可以改進這一點,請這樣做我可以從中學習。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.