Home > front end >  How to pass viewmodel to a viewcontroller using navigationController?
How to pass viewmodel to a viewcontroller using navigationController?

Time:02-21

So i ran into this weird problem.This is my navigation navigation basically it's LoginVC then NavigationController then HomeVC i'm trying to change rootViewcontroller form loginVC to Navigation.HomeVC is itself a rootVC for navigationController. The problem is that i cannot figure out how to pass viewmodel from loginVC to homeVC. This is how i instaniate NavigationController:

loginViewModel.loginStatus.bind { [weak self] isLoggedIn in
        switch isLoggedIn {
        case true:
            print("---login was successfull,transfering to home page---")
            let navController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "customNavigationController") as! UINavigationController
            self!.view.window?.rootViewController = navController
         
        case false:
            AlertManager.initializeAlert(show: .incorrectData, on: self!)
        default: break
        }
    }
}

but i can't figure out how to pass ViewModel to my homeVC

init(_ viewmodel: HomeViewModel) {
    self.homeViewModel = viewmodel
    super.init(nibName: nil, bundle: nil)
}

is there any way to achieve this? or am I doing something fund

CodePudding user response:

If you initialize your HomeVC via Storyboard, you cannot initialize it with your init(viewmodel:) initializer. Storyboard uses init(coder:) initializer to initialize your view controller. So you need set your viewmodel after you initalize your HomeVC. And if you set your HomeVC to root of your UINavigationController on Storybard. You can reach it from UINavigationController's topViewController property.

But if you want to use initializer injection approach to pass your dependencies, then you need to initialize your viewcontrollers programmatically. For example:

loginViewModel.loginStatus.bind { [weak self] isLoggedIn in
        switch isLoggedIn {
        case true:
            print("---login was successfull,transfering to home page---")
            let homeView = HomeVC(HomeViewModel()) // you can replace it with your actual view model
            let navController = UINavigationController(rootViewController: homeView)
            self!.view.window?.rootViewController = navController
         
        case false:
            AlertManager.initializeAlert(show: .incorrectData, on: self!)
        default: break
        }
    }
}

But, in order to initialize your viewcontrollers programmatically, you need to make your VC's design programatically too or you need to use xib files instead of Storyboard.

  • Related