EnvironmentObject
同时更新时,ObservedObject
再次初始化。因此,每次Name
更新时,@EnvironmentObject
的值为空白。
struct MenuView: View {
@EnvironmentObject var order: Order
@ObservedObject var model = DetailsModel()
var body: some View {
NavigationView {
VStack {
Text("Name: \(self.model.name)")
Button(action:{
self.model.name = "Arjun"
}) {
Text("Set Name")
}.padding(.bottom, 30.0)
Button(action:{
self.order.add(item: "item")
}) {
Image(systemName: "cart.badge.plus")
Text("Add to cart")
}.padding(.bottom, 30.0)
}
}
}
}
// DetailsModel
class DetailsModel: ObservableObject {
@Published var name:String = ""
}
我的问题是,@ObservedObject
更新后如何管理@EnvironmentObject
的值?
答案 0 :(得分:1)
SwiftUI 2.0
像{p>一样@StateObject
struct MenuView: View {
@EnvironmentObject var order: Order
@StateObject var model = DetailsModel()
...
SwiftUI 1.0
通过构造函数从外部注入它(具有自己的生命周期)
struct MenuView: View {
@EnvironmentObject var order: Order
@ObservedObject var model: DetailsModel
...