[英]How to Create a UIViewController programmatically with view from storyboard
I have a view controller designed in Main.storyboard
named ProfileViewController
also a corresponding class by that name. 我在Main.storyboard
设计了Main.storyboard
名为ProfileViewController
的视图控制器,该名称也对应于该类。 I can instantiate the viewController like this, 我可以像这样实例化viewController,
UIStoryboard(name: "SignUp", bundle: nil).instantiateViewController(withIdentifier: "ProfileViewController") as? ProfileViewController
However what I'd like to do is instantiate the view controller like this 但是我想做的是像这样实例化视图控制器
let profileViewController = ProfileViewController(/*argument list*/)
Storyboard's view controllers MUST instantiate from storyboard
. 情节提要的视图控制器必须从storyboard
提要实例化。 if you need a custom constructor function (like a initializer), you can define a simple one like this: 如果需要自定义构造函数(如初始化程序),则可以定义一个简单的函数,如下所示:
extension ProfileViewController {
static func new(argument: any) -> ProfileViewController {
let vc = UIStoryboard(name: "SignUp", bundle: nil).instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController
vc.argument = argument
return vc
}
}
Note that if you want to use a real initializer, you can't use storyboard. 请注意,如果要使用真正的初始化程序,则不能使用情节提要。 You may use the view of the designed view controller and assign it to the view in initializer but you will loose other view controller settings. 您可以使用设计的视图控制器的视图,并将其分配给初始化程序中的视图,但是您将失去其他视图控制器设置。
extension ProfileViewController {
convenience init(argument: Any) {
self.init()
self.view = UIStoryboard(name: "SignUp", bundle: nil).instantiateViewController(withIdentifier: "ProfileViewController").view
self.argument = argument
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.