I programatically have multiple View Controllers in an iOS Swift Project. I do not have the storyboards and would like to avoid them if possible. Is there a way to switch to
Swift 3 and Swift 4
let vc = self.storyboard?.instantiateViewController(withIdentifier: "idMyViewControllerName") as! MyViewControllerName
self.present(vc, animated: true, completion: nil)
You can use below code :
var vc = self.storyboard?.instantiateViewControllerWithIdentifier("YourViewController") as! YourViewController;
vc.mode_Player = 1
self.presentViewController(vc, animated: true, completion: nil)
Solved the black screen by adding a navigation controller and setting the second view controller as rootVC.
let vc = ViewController()
var navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil
Just use this : Make sure using nibName otherwise preloaded views of xib will not show :
var vc : ViewController = ViewController(nibName: "ViewController", bundle: nil)
//change this to your class name
self.presentViewController(vc, animated: true, completion: nil)
You can use code:
if let vc = self.storyboard?.instantiateViewController(withIdentifier: "secondViewController") as? secondViewController {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = vc
}
You don't need to instantiate the ViewController in Storyboard just to get present()
ViewController to work. That's a hackish solution.
If you see a black/blank screen when presenting a VC, it might be because you're calling present()
from viewDidLoad()
in the First/RootViewController, but the first View isn't ready yet.
Call present()
from viewDidAppear
to fix this, i.e.:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let yourVC = YourViewController()
self.present(yourVC, animated: true, completion: nil)
}
Once any "View" has appeared in your App, you can start calling present() from viewDidLoad()
.
Using UINavigationController
(as suggested in an answer) is another option, but it might be an overkill to solve this issue. You might end up complicating the user flow. Use the UINavigationController
based solution only if you want to have a NavigatonBar or want to return to the previous view controller.