0

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

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())
    }
}
4

1 回答 1

0

您不能只将几个视图body放入View. 这些视图将如何显示?

您需要将它们包装在堆栈中,具体取决于您的需要,VStackaHStackZStack.

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

struct MainView: View {

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

至于环境对象,您不需要手动将它们注入FirstEnvironmentObjectViewfrom MainView,因为EnvironmentObjects 被注入到下游的视图层次结构中(因此注入到父视图的所有子视图),因此通过将 aUser_Interests_ViewModel作为 anEnvironmentObject注入到MainView,它会自动注入进入所有FirstEnvironmentObjectView创建的 s 里面MainView

于 2021-10-28T11:48:23.870 回答