SwiftUI:我迷路了,当我试图通过环境对象到另一个视图时,使用MVVM



我已经阅读了几乎所有我能找到的关于这种行为的帖子:

No ObservableObject of type BaseViewModel found. A View.environmentObject(_:) for BaseViewModel may be missing as an ancestor of this view

然而,我还是没能完成它。我认为我使用"@EnvironmentObject var vm: BaseViewModel"是错误的。但是当我尝试& @EnvironmentObject var vm = BaseViewModel()", BaseViewModel()将要求付款人,所以它将是BaseViewModel(付款人:)。这是我的代码

struct Payer: Identifiable {
var id = UUID().uuidString
var name : String
var offset : CGFloat = 0
}

在我的ViewModel文件中

class BaseViewModel: ObservableObject {

//* The problem * //
@Published var payer: Payer 
//* The problem * //

@Published var payers = [
Payer( name: "AA"),
Payer( name: "BB"),
Payer( name: "CC"),
]

init(payer: Payer) {
self.payer = payer
}
}

最后在我的ContentView

struct ContentView: View {
@EnvironmentObject var vm : BaseViewModel
var body: some View {
BaseView()
.environmentObject(self.vm)
}
}

您需要将其注入到创建ContentView的位置,如

@main
struct YourApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(BaseViewModel(player: Payer( name: "AA"))
}
}
}

struct ContentView: View {
@EnvironmentObject var vm : BaseViewModel
var body: some View {
BaseView()
//.environmentObject(self.vm)  << not needed here !!
}
}

:你可以创建

struct ContentView: View {
@StateObject var vm = BaseViewModel(player: Payer( name: "AA") // << create !!
var body: some View {
BaseView()
.environmentObject(self.vm)  << inject !!
}
}

你必须从你的应用程序的根注入你的数据模型,那是从主根结构。

import SwiftUI
struct Payer: Identifiable {
var id = UUID().uuidString
var name : String = "ABCD"

var offset : CGFloat = 0
}
class BaseViewModel: ObservableObject {

//* The problem * //
@Published var payer: Payer
//* The problem * //

@Published var payers = [
Payer( name: "AA"),
Payer( name: "BaB"),
Payer( name: "CC"),
]

init(payer: Payer) {

self.payer = payer
}
}
struct ContentView: View {
@EnvironmentObject var vm : BaseViewModel
var body: some View {
Text(vm.payer.name)
}
}

@Main -:

import SwiftUI
@main
struct WaveViewApp: App {

@StateObject var dataController:BaseViewModel

init() {
let payer = Payer()
let model = BaseViewModel(payer:payer)
_dataController = StateObject(wrappedValue: model)
}

var body: some Scene {
WindowGroup {
ContentView().environmentObject(dataController)
}
}
}

相关内容

  • 没有找到相关文章

最新更新