将数据传递给实例化的View Controller

时间:2017-10-24 07:25:23

标签: swift swift3 uiviewcontroller uinavigationcontroller

假设我们有一个嵌入UINavigationController的视图控制器。我们想在成功实例化之后呈现它。例如:

if let navigationController = UIStoryboard.init(name: "Main", bundle: nil).instantiatedViewController(withIdentifier: "UINavigationController") as? UINavigationController {

 self.present(navigationController, animated: true, completion: nil)

}

嗯它的确有效,但我们在这里遇到了问题。因为我们想通过导航控制器将数据传递给视图控制器。到目前为止我尝试过的:

if let navigationController = UIStoryboard.init(name: "Main", bundle: nil).instantiatedViewController(withIdentifier: "UINavigationController") as? UINavigationController {

  let viewController = navigationController.topViewController as! CustomViewController
  viewController.stringValue = "Value" 

 self.present(navigationController, animated: true, completion: nil)

  }

它完美无缺。但我认为这不是最好的方式。没有其他方法或者它是正确的解决方案吗?

2 个答案:

答案 0 :(得分:2)

您当前的方法本身就足够好了。 不过,如果你想要一种更好的做事方式,我认为你应该研究协调员模式。

ViewController承担初始化/配置/呈现后续ViewControllers的责任,这很奇怪。此外,当您想要移动一些东西时,事情变得非常棘手,例如,在身份验证流程中更改一些ViewControllers。 ViewControllers变得依赖于其他ViewControllers,整个事情变得非常混乱。

使用协调器并非易事,因为您可能需要更改应用的整个架构。我觉得你现在应该坚持当前的实施。但是,如果你想要它,这里有一些资源可以帮助你跳跃。

Coordinators Redux (Theory behind Coordinators)

An iOS Coordinator Pattern (pratical example)

答案 1 :(得分:0)

为什么不尝试使用协议。你的代码将更具可读性,我认为这是最好的方法之一:)