swiftswiftuiswiftui-environmentenvironmentobject

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


When calling one view environment object in main view thats ok build successful but when I call second view environment object its throw an error extra argument in call.

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

Solution

  • You cannot just throw in several views into the body of a View. How would those views be displayed?

    You need to wrap them in a stack, depending on your needs, either a VStack, HStack or ZStack.

    If you want them to be vertically stacked for instance, use a VStack.

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

    As for the environment object, you don't need to manually inject them into FirstEnvironmentObjectView from MainView, because EnvironmentObjects are injected into the view hierarchy downstream (so to all subviews of the parent view) and hence by injecting a User_Interests_ViewModel as an EnvironmentObject into MainView, it gets automatically injected into all FirstEnvironmentObjectViews created inside MainView.