在 Swift 中从情节提要中实例化 ViewController
Instantiation of ViewControllers from storyboard in Swift
我有一个 UIViewController
看起来有点像这样:
class ProfileViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, ... {
...
convenience init(name: String) {
print("Init with student: \(name)")
self.init()
}
...
}
我有一个相应的 Storyboard 布局,嵌入 UINavigationViewController,linked 到 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
它需要正确显示的信息。
如何创建我的 ViewControllers,link 故事板的布局并使用自定义初始化函数?这甚至可能吗?
非常感谢任何建议!!
使用故事板时,您不能使用自定义初始化程序。您需要直接设置 属性 或在创建视图控制器实例后使用配置函数。
我有一个 UIViewController
看起来有点像这样:
class ProfileViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, ... {
...
convenience init(name: String) {
print("Init with student: \(name)")
self.init()
}
...
}
我有一个相应的 Storyboard 布局,嵌入 UINavigationViewController,linked 到 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
它需要正确显示的信息。
如何创建我的 ViewControllers,link 故事板的布局并使用自定义初始化函数?这甚至可能吗?
非常感谢任何建议!!
使用故事板时,您不能使用自定义初始化程序。您需要直接设置 属性 或在创建视图控制器实例后使用配置函数。