SwiftUi Extra Argument in Call 在主视图中调用@EnvironmentObject 的两个视图时

SwiftUi Extra Argument in Call When calling two views of @EnvironmentObject in main view

在主视图中调用一个视图环境对象时,构建成功,但是当我调用第二个视图环境对象时,它在调用中抛出一个错误额外参数。

struct mainView: View{

    @EnvironmentObject var userInterestVM: User_Interests_ViewModel
  

    var body: some View {
        FirstEnvironmentObjectView()
        FirstEnvironmentObjectView()      //<--(error: Extra Argument in call)

        // if i call first environment with argument like that

        FirstEnvironment(UserInterestsVM: <what I put here>)  
        // what should I put in the argument)
     
    }
}


struct FirstEnvironmentObjectView: View {

    @EnvironmentObject var UserInterestsVM: User_Interests_ViewModel

    var body: some View {
        Text("check by default values of model.").onTapGesture {
            print("fitness \(UserInterestsVM.fitness)")    
    }
}


struct FirstEnvironmentObjectView_Previews: PreviewProvider {
    static var previews: some View {
        testing()
            .environmentObject(User_Interests_ViewModel())
    }
}

您不能只将几个视图放入 Viewbody 中。这些视图将如何显示?

您需要根据需要将它们打包成一个堆栈,可以是 VStackHStackZStack.

例如,如果您希望它们垂直堆叠,请使用 VStack

struct MainView: View {

    @EnvironmentObject var userInterestVM: User_Interests_ViewModel
  
    var body: some View {
        VStack {
            FirstEnvironmentObjectView()
            FirstEnvironmentObjectView()     
        }
    }
}

至于环境对象,你不需要手动将它们从MainView注入到FirstEnvironmentObjectView,因为EnvironmentObjects被注入到下游的视图层次结构中(所以父视图的所有子视图),因此通过将 User_Interests_ViewModel 作为 EnvironmentObject 注入 MainView,它会自动注入到 MainView 中创建的所有 FirstEnvironmentObjectView .