Lorenzo Neri Lorenzo Neri - 3 years ago 106
Swift Question

Load ViewController through hard code with storyBoardID

I'm trying to load a view through this code:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
//let vc = self
let vc = storyboard.instantiateViewController(withIdentifier: "loginView") as! RegistrationViewController
self.present(vc, animated: true, completion: nil)


The result is:

2017-07-24 16:39:48.135 XXX [8689:286531] Warning: Attempt to present <XXX.RegistrationViewController: 0x7f8246206280> on <XXX.LaunchAppCheck: 0x7f8243d06bd0> whose view is not in the window hierarchy!


I've already seen in another question to try with
viewDidAppear()
, but the problem still persist.

Answer Source

Probably this line is bothering you:

let storyboard = UIStoryboard(name: "Main", bundle: nil)

This is instantiating another storyboard other than your actual storyboard.

This is the code I use:

let vc: SettingsViewController = self.storyboard!.instantiateViewController(withIdentifier: "SettingsViewController") as! SettingsViewController
self.present(vc, animated: true, completion: nil)

You should not try to load it in simultaneously with another viewController, i.e. viewDidLoad() as at this point it is not on the stack yet.

If you really need to present 2 viewControllers at same time, try to call the second one using a delay:

vc = self.storyboard!.instantiateViewController(withIdentifier: "SettingsViewController") as! SettingsViewController
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
         self.present(vc, animated: true, completion: nil)
    }

Maybe it helps.

Don't forget to set the id of your view in your Identity Inspector.

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download