0
struct ContentView {
    @ObservedObject var annotationsVM = AnnotationsVM()
    //I'd like to pass in the ViewModel() declared below into annotationsVM like AnnotationsVM(VModel: Vmodel)
    @ObservedObjects var VModel = ViewModel()

    var body: some View {
        //All the SwiftUI view setup is in here
    }
}

class AnnotationsVM: ObservableObject {
    @ObservedObject var VModel = ViewModel()
    //I'd like to pass in the VModel in content view like: @ObservedObject var VModel: VModel
}

显然,我不能像我想要的那样在 ContentView 创建时直接传递 VModel,因为 VModel 对象尚未创建,因此无法访问......

回顾:我想将在 ContentView 中声明的 VModel 实例传入 annotationsVM 实例(也在 ContentView 中声明)

4

1 回答 1

1

你可以这样做init

struct ContentView {
    @ObservedObject var annotationsVM: AnnotationsVM
    @ObservedObject var vModel: ViewModel

    init() {
        let vm = ViewModel()
        vModel = vm
        annotationsVM = AnnotationsVM(vModel: vm)
    }

    var body: some View {
        //All the SwiftUI view setup is in here
    }
}

class AnnotationsVM: ObservableObject {
    var vModel: ViewModel

    init(vModel: ViewModel) {
        vModel = vModel
    }
}

而且您@ObservedObject只能在View.

注意:最好在 init 中将 ViewModels 作为参数传递以遵循Dependency Injection模式。

于 2020-05-31T15:52:38.650 回答