How to load UIViewController programmatically from

2019-02-08 17:49发布

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?

self.presentViewController(ResultViewController(), animated: true, completion: nil)

2条回答
叛逆
2楼-- · 2019-02-08 18:09

Full Swift 3 code including instantiation of Storyboard:

let storyboard = UIStoryboard.init(name: "Main", bundle: Bundle.main)

if let mainViewController = storyboard.instantiateInitialViewController() {
    present(mainViewController, animated: false, completion: nil)
}
查看更多
Ridiculous、
3楼-- · 2019-02-08 18:29

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.

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.

enter image description here

查看更多
登录 后发表回答