15

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)
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
ThatHybrid
  • 383
  • 2
  • 3
  • 9
  • possible duplicate of [How to call a View Controller programmatically?](http://stackoverflow.com/questions/16134361/how-to-call-a-view-controller-programmatically) – brainray Aug 19 '15 at 09:11

3 Answers3

38

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

swiftBoy
  • 35,607
  • 26
  • 136
  • 135
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
7

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)
}
Justin Vallely
  • 5,932
  • 3
  • 30
  • 44
1

enter image description here

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)
 }
mohsen
  • 4,698
  • 1
  • 33
  • 54