问题描述
我正在 SwiftUI 中尝试练习 @EnvironmentObject
工具.ContentView
中的共享对象 User
init.
当我从 ContentView 切换到 NameView 时效果很好.
但是,从 NameView 到 AgeView 失败了.(请查看错误消息和代码会话)
I'm trying practice @EnvironmentObject
tool in SwiftUI.
the share object User
init in ContentView
.
When I switch from ContentView to NameView work very well.
But, from NameView to AgeView is failed. (take a look error message and Code session, please)
错误信息
Fatal error: No ObservableObject of type User found.
有人能给我建议吗?我错过了什么吗?谢谢
Could someone give me advice? Do I miss something? thx
代码
init "User" type in contentView
NavigationView
+-----------+ +--------+ +-------+
|ContentView+--NavigationLink-->|NameView+--NavigationLink-->|AgeView|
+-----------+ +--------+ +-------+
final class User: ObservableObject {
@Published var name: String
@Published var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
struct ContentView: View {
var user: User = User(name: "SomeName", age: 44)
var body: some View {
NavigationView {
VStack {
Text("name: \(self.user.name) age: \(self.user.age)")
NavigationLink(destination: NameView().environmentObject(self.user)) {
Text("Show Name")
}
}
}
}
}
struct NameView: View {
@EnvironmentObject var user: User
var body: some View {
VStack {
Text("name: \(self.user.name)")
NavigationLink(destination: AgeView()) {
Text("Show Age")
}
}
}
}
struct AgeView: View {
@EnvironmentObject var user: User
var body: some View {
VStack {
Text("age: \(self.user.age)")
}
}
}
推荐答案
希望通过以下示例对您有所帮助:
Hope this helps you with the following example:
我们有我们的模型,它是可观察的,并且拥有它的所有变量已发布:
We have our model which is Observable and has all it's variables Published:
class A: ObservableObject {
@Published var id: String = ""
@Published var value: String = ""
}
将其用作 EnvironmentObject 时,请确保在 SceneDelegate.swift 中将其设置如下:
When using it as an EnvironmentObject make sure you'd set this in the SceneDelegate.swift as follows:
let example = Example()
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: example.environmentObject(A()))
self.window = window
window.makeKeyAndVisible()
}
然后我们可以在所有视图中使用这个EnvironmentObject:
Then we can use this EnvironmentObject in all Views:
struct Example: View {
@EnvironmentObject var obj: A
var body: some View {
Button(action: {
self.obj.value = "Hi im changed"
}) {
Text("Change me")
}
}
}
有时当你想更新这个对象中的数据时,xCode 可能会给你一个关于'No EnvironmentObject set for ... classname etc.' 的错误,在这种情况下你需要传递一个 EnvironmentObject到目标视图:
Sometimes when you want to update data in this object, xCode may give you an error about 'No EnvironmentObject set for ... classname etc.', in this case you need to pass an EnvironmentObject to the destination view:
DestinationView().environmentObject(self.A)
希望这会有所帮助,祝你好运!
Hope this helps, goodluck!
这篇关于对 SwiftUI 中的 @EnvironmentObject 感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!