Swift 3 - loading multiple ViewControllers at laun

2020-04-29 17:04发布

问题:

I am working on making a tabbed app. It has a TabBarController and 4 ViewControllers attached to it.

By default, at launch only FirstViewController is loaded. I would like to load both FirstViewController and SecondViewController at start before switching to the second view via tab menu.

What i tried so far is that I created custom MyTabBarController class and tried to use

var sv = SecondViewController()
sv.loadView()

in ViewDidLoad(), but it caused a fatal error during loading, because (my guess) mapView element from storyboard was not loaded.

What is the correct way to simultaneously load the two viewControllers which use storyboard elements? All my other tries have not been successful so far.

回答1:

Add in your main view controller

var secondViewController:UIViewController!

And in your viewDidLoad:

secondViewController: UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "yourIdentifier") as! SecondViewController

That's it. When you want to present it, use:

self.present(secondViewController, animated: true, completion: nil)