swift - 如何从 NSViewRepresentable / UIViewRepresentable 的 Coordinator 类中访问 EnvironmentObject?
问题描述
我有一个名为 appState 的 EnvironmentObject,可以通过我的一些视图访问它以共享数据/状态。我在视图中使用它们的方式是这样的:
struct MetalView: NSViewRepresentable {
@EnvironmentObject var appState: AppState
如何从视图的 Coordinator 类访问 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 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 程序员......
如果高级程序员可以改进这一点,请这样做我可以从中学习。
推荐阅读
- asp.net-core - How do I prevent ASP.NET Core detecting literal text I write as having special significance to the layout engine?
- php - SQLSTATE[22P02]:无效的文本表示错误
- laravel - Update payment descriptor with Stripe payment system
- c# - 使用 Powershell 创建脚手架项目
- java - 使用 Docker 部署 Java Web 项目失败 [无主清单属性]
- spring - Failed Let's Encrypt standalone authorization procedure
- python - Python SQlite FileNotFoundError:[Errno 2] 没有这样的文件或目录:'x.txt'
- unity3d - Serialization of a list of custom objects in unity
- javascript - 是否可以在重新加载后继续运行的浏览器控制台中添加一个间隔?
- c# - 在 EntityFramework 的拦截中获取实体类型