我有一個viewController,它設計在Storyboard 的一頁中,是應用程式的初始/主螢屏。我正在嘗試從 api 獲取一些資料,然后在我的螢屏上更新一個 collectionView。我之前確實獲取過資料,但現在我正在嘗試在應用程式中構建MVVM結構。
我嘗試將應用程式轉換為 MVVM 的方式基本上是;構建視圖模型和初始化 的ViewController與視圖模型使用依賴注入。你可以看到我的依賴注入如下:
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 上沒有任何內容,它是具有 1 頁的初始 viewController。只是想了解為什么在我的 ViewController 正在初始化時我的 viewModel 根本沒有被初始化。

uj5u.com熱心網友回復:
使用 Storyboard 時,會呼叫編碼器 init。基本上你永遠不會呼叫你的init。
您可以在創建 viewController 時傳遞 VM,例如
let viewController = // init the VC
viewController.viewModel = viewModel // create the VM you want to pass here.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/404629.html
標籤:
