如何将环境对象传递到ViewModel SwiftUI
我使用一个函数通过API端点从数据库中获取配方。它包含3个参数,脂肪、碳水化合物、蛋白质,我希望这些值等于我的环境对象(或两个环境对象的计算)fatGoal-fatProgress等。但是,在我的viewModel中,我在尝试使用我的环境对象时出现以下错误:如何将环境对象传递到ViewModel SwiftUI,swift,swiftui,Swift,Swiftui,我使用一个函数通过API端点从数据库中获取配方。它包含3个参数,脂肪、碳水化合物、蛋白质,我希望这些值等于我的环境对象(或两个环境对象的计算)fatGoal-fatProgress等。但是,在我的viewModel中,我在尝试使用我的环境对象时出现以下错误: Thread 1: Fatal error: No ObservableObject of type UserInfoModel found. A View.environmentObject(_:) for UserInfoModel m
Thread 1: Fatal error: No ObservableObject of type UserInfoModel found. A View.environmentObject(_:) for UserInfoModel may be missing as an ancestor of this view.
这是我的ViewModel服务文件:
import SwiftUI
import Combine
import Foundation
class MealViewModel: ObservableObject {
@Published var nutrients: [RecipieAPI] = []
@EnvironmentObject var person: UserInfoModel
@State public var fat = 0
@State public var carbs = 0
@State public var protein = 0
init() {
fetchNutrients()
}
func fetchNutrients() {
NetworkServices.fetchNutrients(maxProtein: self.person.recipeNutrientsSearch.protein , maxFat: self.person.recipeNutrientsSearch.fat, maxCarbs: self.person.recipeNutrientsSearch.carb, number: 4) { (nutrients, error) in
if let error = error {
print(error)
} else {
if let nutrientList = nutrients as? [RecipieAPI] {
self.nutrients = nutrientList
}
}
}
}
}
错误被调用
NetworkServices.fetchNutrients(maxProtein: self.person.recipeNutrientsSearch.protein , maxFat: self.person.recipeNutrientsSearch.fat, maxCarbs: self.person.recipeNutrientsSearch.carb, number: 4) { (nutrients, error) in
任何帮助都将不胜感激
编辑
内容视图:
import SwiftUI
struct ContentView: View {
//Instantiating an object of UserInfo Model (referenced in App.swift too
@EnvironmentObject var person: UserInfoModel
init() {
//Setting appearance of UI colour
UITabBar.appearance().backgroundColor = ColourManager.UIColour1
}
var body: some View {
TabView {
ProfileView().tabItem ({
Text("Profile")
}).tag(0)
TrackerView().tabItem ({
Text("Tracker")
}
).tag(1)
AddView().tabItem ({
Text("Add")
}).tag(2)
MealView().tabItem ({
Text("Meals")
}).tag(3)
}.accentColor(ColourManager.Colour3)
.environmentObject(UserInfoModel())
}
}
环境对象类:UserinfoModel:
import Foundation
class UserInfoModel: ObservableObject {
struct UserInfo: Identifiable {
var id = UUID()
var firstName: String
var height: Double
var weight: Double
var gender: String
var age: Double
var activityLevel: String
var BMR: Double
}
struct AddedFoods:Identifiable{
var name: String = ""
var totalCals: Double = 0
var totalProtein: Double = 0
var totalCarbs: Double = 0
var totalFat: Double = 0
var id = UUID().uuidString
//Your other properties
}
struct DailyCalorieGoals: Identifiable{
var id = UUID()
var calorieGoal: Double
var fatGoal: Double
var proteinGoal: Double
var carbGoal: Double
}
struct CurrentCalorieProgress: Identifiable{
var id = UUID()
var calorieProgress: Double
var fatProgress: Double
var carbProgress: Double
var proteinProgress: Double
}
struct SearchRecipeCalories: Identifiable{
var id = UUID()
var fat: Int
var carb: Int
var protein: Int
}
@Published var personUserInfo = UserInfo.init(firstName: "", height: 0, weight: 0, gender: "", age: 0, activityLevel: "", BMR: 0)
@Published var personDailyCalorieGoals = DailyCalorieGoals.init(calorieGoal: 2400, fatGoal: 40, proteinGoal: 40, carbGoal: 40)
@Published var personCurrentCalorieProgress = CurrentCalorieProgress.init(calorieProgress: 1200, fatProgress: 12, carbProgress: 5, proteinProgress: 30)
@Published var recipeNutrientsSearch = SearchRecipeCalories.init(fat: 0, carb: 0, protein: 0)
}
环境对象必须由anscestor视图提供
导入快捷界面
@主要
结构pro2App:App{//MealViewModel不是环境对象,环境对象是UserInfoModel,这是您的错误,还是它意味着调用ViewModel?您是对的,我只是使用了错误的类名,但规则是相同的。不幸的是,我得到了相同的错误:线程1:致命错误:找不到UserInfoModel类型的ObservableObject。a View.eUserInfoModel的NVEnvironmentObject(u:)可能作为此视图的祖先丢失。我将在帖子中添加我的contentView,以便您查看UserInfoModel代码在哪里?
import SwiftUI
@main
struct pro2App: App { // <<: Here: your app name!
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(MealViewModel()) // <<: Here!
.environmentObject(UserInfoModel.shared) // <<: Here!
}
}
}
class MealViewModel: ObservableObject {
@Published var nutrients: [RecipieAPI] = []
let person: UserInfoModel.shared // <<: Here
@State public var fat = 0
@State public var carbs = 0
@State public var protein = 0
init() {
fetchNutrients()
}
func fetchNutrients() {
NetworkServices.fetchNutrients(maxProtein: self.person.recipeNutrientsSearch.protein , maxFat: self.person.recipeNutrientsSearch.fat, maxCarbs: self.person.recipeNutrientsSearch.carb, number: 4) { (nutrients, error) in
if let error = error {
print(error)
} else {
if let nutrientList = nutrients as? [RecipieAPI] {
self.nutrients = nutrientList
}
}
}
}
}
class UserInfoModel: ObservableObject {
static let shared: UserInfoModel = UserInfoModel() // <<: Here
struct UserInfo: Identifiable {
var id = UUID()
var firstName: String
var height: Double
var weight: Double
var gender: String
var age: Double
var activityLevel: String
var BMR: Double
}
struct AddedFoods:Identifiable{
var name: String = ""
var totalCals: Double = 0
var totalProtein: Double = 0
var totalCarbs: Double = 0
var totalFat: Double = 0
var id = UUID().uuidString
//Your other properties
}
struct DailyCalorieGoals: Identifiable{
var id = UUID()
var calorieGoal: Double
var fatGoal: Double
var proteinGoal: Double
var carbGoal: Double
}
struct CurrentCalorieProgress: Identifiable{
var id = UUID()
var calorieProgress: Double
var fatProgress: Double
var carbProgress: Double
var proteinProgress: Double
}
struct SearchRecipeCalories: Identifiable{
var id = UUID()
var fat: Int
var carb: Int
var protein: Int
}
@Published var personUserInfo = UserInfo.init(firstName: "", height: 0, weight: 0, gender: "", age: 0, activityLevel: "", BMR: 0)
@Published var personDailyCalorieGoals = DailyCalorieGoals.init(calorieGoal: 2400, fatGoal: 40, proteinGoal: 40, carbGoal: 40)
@Published var personCurrentCalorieProgress = CurrentCalorieProgress.init(calorieProgress: 1200, fatProgress: 12, carbProgress: 5, proteinProgress: 30)
@Published var recipeNutrientsSearch = SearchRecipeCalories.init(fat: 0, carb: 0, protein: 0)
}