如何在同一Struct上管理@ObservedObject和@EnvironmentObject?

时间:2020-10-19 06:39:59

标签: swift xcode swiftui

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的值?

1 个答案:

答案 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
...