gpt4 book ai didi

ios - UIViewControllers iOS swift 中的依赖注入(inject)

转载 作者:搜寻专家 更新时间:2023-11-01 06:26:44 25 4
gpt4 key购买 nike

首先我检查了this post而且没用

我想在从一个 Controller 到另一个 Controller 的导航上应用依赖注入(inject),

假设我有 Controller A:

import UIKit

class A: UIViewController {

}

和 Controller B:

import UIKit

class B: UIViewController {

var name : String!

}

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

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

我想转换我的代码以便通过初始化器使用依赖注入(inject)。

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

提前谢谢。

最佳答案

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

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

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

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

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

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

  1. 从 Storyboard 实例化 VC
  2. 实例化数据结构
  3. 将数据赋值给VC的var data: Data!
  4. 使用其中的所有注入(inject)变量

关于ios - UIViewControllers iOS swift 中的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53305553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com