简体   繁体   中英

How to load UIViewController programmatically from storyboard?

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)

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.

在此处输入图片说明

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)
}

在此处输入图片说明

SWIFT 5.2

first, you should define a storyboardID for viewcontroller and after use this code

 let storyboard = UIStoryboard(name: "Main", bundle: nil) // type storyboard name instead of Main
 if let myViewController = storyboard.instantiateViewController(withIdentifier: "myViewControllerID") as? CourseDetailVC {
       present(myViewController, animated: true, completion: nil)
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM