【问题标题】:Instantiation of ViewControllers from storyboard in Swift在 Swift 中从情节提要中实例化 ViewController
【发布时间】:2017-02-03 10:19:53
【问题描述】:

我有一个UIViewController,看起来有点像这样:

class ProfileViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, ... { 
    ...

    convenience init(name: String) {
        print("Init with student: \(name)")
        self.init()
    }
    ...
}

我有一个相应的故事板布局,嵌入在 UINavigationViewController 中,链接到 UITabBarController。这似乎是设计布局的最简单方法,并且非常适合只需要此 VC 的一个实例(这就是应用程序最初的设计方式)。

我现在想从这个单一设计(1 到 3 之间)创建多个选项卡,并以编程方式传递 VC 初始化信息,但我不确定执行此操作的最佳方法 - 正如您在上面看到的我添加了一个基于我已经完成的一些阅读的便利 init 函数,因为这似乎是一个很好的起点。

根据故事板布局创建新的命名选项卡很容易,如下所示:

for user in (users)! {
     let storyboard = UIStoryboard(name: "Main", bundle: nil)
     let controller = storyboard.instantiateViewController(withIdentifier: "profileNC") 
     controller.tabBarItem.title = user.name
     newTabs?.insert(controller, at: 0)
}
self.viewControllers = newTabs

但是,这样做我无法调用 init 函数来传递 UIViewController 正确显示所需的信息。

如何创建我的 ViewController、将布局链接到 Storyboard 并使用自定义的 init 函数?这甚至可能吗?

任何建议都非常感谢!

【问题讨论】:

  • 只是为了理解,为什么要在创建 UIViewController 时调用自定义 init。我的意思是强迫你创建一个自定义初始化器的约束是什么?
  • 按照@Paulw11 的回答,我发现我可以实例化NC,获取子VC,转换为ProfileViewController,然后直接设置变量,这似乎是一种明智的方法-或至少到目前为止它还在工作!我最初认为 ViewDidLoad 会在我设置变量之前被调用,所以我需要使用自定义的 Init - 但在反思时这有点傻; View 与 Class 不同。

标签: ios swift uiviewcontroller uistoryboard


【解决方案1】:

使用情节提要时,您不能使用自定义初始化程序。创建后,您需要直接设置属性或在视图控制器实例上使用配置函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 2015-05-19
    • 2015-12-29
    • 1970-01-01
    相关资源
    最近更新 更多