ios 如何从故事板以编程方式加载 UIViewController?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25474115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to load UIViewController programmatically from storyboard?
提问by ThatHybrid
I created a UIViewController in my Main.storyboard with a few buttons and labels. I'm trying to switch to that view controller using self.presentViewController but it will not load the view from storyboard. It will only load a blank black screen by default. Any idea on how to load the view from what i've created in storyboard?
我在 Main.storyboard 中创建了一个 UIViewController ,带有几个按钮和标签。我正在尝试使用 self.presentViewController 切换到该视图控制器,但它不会从故事板加载视图。默认情况下它只会加载一个空白的黑屏。关于如何从我在故事板中创建的内容加载视图的任何想法?
self.presentViewController(ResultViewController(), animated: true, completion: nil)
回答by Mick MacCallum
The way you're doing this just creates a new instance of your view controller. It does not create one from the prototype you've defined in Interface Builder. Instead, you should be using this, where "SomeID" is a storyboard ID that you've assigned to your view controller in Interface Builder.
您这样做的方式只是创建视图控制器的新实例。它不会根据您在 Interface Builder 中定义的原型创建一个。相反,您应该使用它,其中“SomeID”是您在 Interface Builder 中分配给视图控制器的故事板 ID。
if let resultController = storyboard!.instantiateViewControllerWithIdentifier("SomeID") as? ResultViewController {
presentViewController(resultController, animated: true, completion: nil)
}
You can assign a storyboard ID to your view controller in Interface Builder's identity inspector.
您可以在 Interface Builder 的身份检查器中为您的视图控制器分配故事板 ID。
回答by Justin Vallely
Full Swift 3 code including instantiation of Storyboard:
完整的 Swift 3 代码,包括 Storyboard 的实例化:
let storyboard = UIStoryboard.init(name: "Main", bundle: Bundle.main)
if let mainViewController = storyboard.instantiateInitialViewController() {
present(mainViewController, animated: false, completion: nil)
}