将 MVVM 与依赖注入和 Storyboard 结合使用

Using MVVM with dependency Injection and Storyboard

我有一个 viewController,它是在 故事板 的一页中设计的 initial/main 应用程序的屏幕。我正在尝试从 api 获取一些数据,然后在我的屏幕上更新一个 collectionView。我之前确实获取过数据,但现在我正在尝试在应用程序中构建一个 MVVM 结构。

我尝试将应用程序转换为 MVVM 的方式基本上是;构建 ViewModel 使用 ViewModel[ 初始化 ViewController =40=] 使用依赖注入。你可以看到我的依赖注入如下:

class ViewController: UIViewController {
    
//MARK: - Properties

private var viewModel: ViewControllerViewModel? = nil

//MARK: - Lifce Cycle

override func viewDidLoad() {
    super.viewDidLoad()
}
    
//    //MARK: - Init
init(with viewModel: ViewControllerViewModel) {
    self.viewModel = viewModel
    super.init(nibName: nil, bundle: nil)
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
  }
}

但问题是,我的 viewModel 根本没有被初始化。我确实在 ViewModel 的 init() 中放置了一些断点,但它们永远不会被击中,下面的 ViewModel 也永远不会执行。就 MVVM 设计模式而言,我在这里缺少什么?

class ViewControllerViewModel {

init() {

   }
}

注意:我在 SceneDelegate 上调用 viewController,如下所示。我如何使用故事板初始化 ViewController,如下所示?:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    guard let _ = (scene as? UIWindowScene) else { return }

    DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
        self?.window?.rootViewController = UIStoryboard(name: "PopularMovies", bundle: nil).instantiateInitialViewController()
        self?.window?.makeKeyAndVisible()
    }
    
}

图片:

  • 我的 viewController 上面什么都没有,是第一个 viewController,只有 1 页。只是想了解为什么我的 ViewController 正在初始化时我的 viewModel 根本没有被初始化。

使用情节提要时,将调用编码器 init。基本上你永远不会调用你的 init.

您可以在创建 viewController 时传递虚拟机,例如

let viewController = // init the VC
viewController.viewModel = viewModel // create the VM you want to pass here.