UIViewControllers iOS swift中的依赖注入

Mhm*_*izk 2 dependency-injection ios swift

首先我检查了这篇文章,它没有用

我想对从控制器到另一个控制器的导航应用依赖注入,

假设我有控制器 A :

import UIKit

class A: UIViewController {

}
Run Code Online (Sandbox Code Playgroud)

和控制器 B :

import UIKit

class B: UIViewController {

       var name : String!

}
Run Code Online (Sandbox Code Playgroud)

我正在以这种方式从 A 导航到 B:

let bViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "BVC")
as! B
bViewController.name = "HelloWorld"
self.navigationController?.pushViewController(bViewController, animated: true)
Run Code Online (Sandbox Code Playgroud)

我想转换我的代码,以便通过初始化程序使用依赖注入。

如果可以做到这一点,任何人都可以提出建议,如果可以做到如何?

提前谢谢。

Pet*_*kov 5

这是不可能的,因为您使用故事板。当您通过instantiateViewController方法从 Storyboard 实例化 ViewController 时,它使用required init?(coder aDecoder: NSCoder)初始化程序。

如果您想使用自定义初始化程序,则需要摆脱 Storyboards 并UIViewController仅从代码或xib文件创建。所以你将能够做到这一点:

import UIKit

class B: UIViewController {
    var name: String!

    init(name: String) {
        self.name = name
        super.init(nibName: nil, bundle: nil) # or NIB name here if you'll use xib file
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}
Run Code Online (Sandbox Code Playgroud)

您还需要提供,init(coder...)因为每个 UI 元素都可以从 Storyboard 实例化。但是您可以保留默认super调用,因为您不会使用它。

另一种选择是static在问题开头的帖子中使用ViewController 中的方法。但实际上它也在 ViewController 初始化之后分配变量。

所以现在没有通过初始化程序的 DI。我建议对struct需要注入 VC 的所有数据使用单独的。这个结构体将包含所有必要的字段,所以你不会错过任何一个。你的典型流程是:

  1. 从 Storyboard 实例化 VC
  2. 实例化Data结构
  3. 将数据分配给 VC var data: Data!
  4. 使用所有注入的变量

  • 从 iOS 13 开始这是可能的,请参阅下面我关于使用“UIStoryboard”方法“instantiateViewController(identifier:creator:)”的答案。 (2认同)