一个 ObservedObject 需要接受另一个 ObservedObject 作为参数;你怎么做到这一点?
One ObservedObject needs to take in another ObservedObject as an argument; how do you do this?
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中声明)
您可以在 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
}
}
并且您只能在 View
中使用 @ObservedObject
。
注意:最好在 init 中将 ViewModel 作为参数传递以遵循 Dependency Injection
模式。
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中声明)
您可以在 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
}
}
并且您只能在 View
中使用 @ObservedObject
。
注意:最好在 init 中将 ViewModel 作为参数传递以遵循 Dependency Injection
模式。