【问题标题】:Passing data to the instantiated View Controller将数据传递给实例化的视图控制器
【发布时间】:2017-10-24 07:25:23
【问题描述】:

假设我们有一个嵌入到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)

  }

这是完美的工作。但我认为这不是最好的方法。没有其他方法还是正确的解决方案?

【问题讨论】:

    标签: swift swift3 uiviewcontroller uinavigationcontroller


    【解决方案1】:

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

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

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

    Coordinators Redux (Theory behind Coordinators)

    An iOS Coordinator Pattern (pratical example)

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 你是什么意思?协议是什么?
      • 试着具体一点,然后给出答案。提供一个协议示例,展示与作者实现相比的好处
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-20
      相关资源
      最近更新 更多