I have not found relevant and up to date answers in the posts related to this question.
I would like to load all viewcontrollers on launch. Currently it launches as expected but when I tap on a bar item (the first time) there is a slight delay to load it because it has not been loaded yet.
How can I do that is Swift ?
Thanks.
To preload a UIViewController
's view, simply access its view
property:
let _ = myViewController.view
To preload all view controllers on a UITabBarController
, you can do:
if let viewControllers = tabBarController.viewControllers {
for viewController in viewControllers {
let _ = viewController.view
}
}
Or a bit more compactly:
tabBarController.viewControllers?.forEach { let _ = $0.view }
Combining Robert's and M. Daigle's solution I came up with something like this:
for viewController in tabBarController?.viewControllers ?? [] {
if let navigationVC = viewController as? UINavigationController, let rootVC = navigationVC.viewControllers.first {
let _ = rootVC.view
} else {
let _ = viewController.view
}
}
Add this to the ViewDidLoad of your first ViewController and should do the trick...
Robert's answer above worked for me, but I had UINavigationControllers as my initial view controllers for each tab. Therefore I had to call
viewControllers.forEach { $0.view }
within my UINavigationControllers in order for their root view controllers to be loaded as well. Hope that helps Sam out.
If you want to prepare both submissions and subcontrollers, you also have to call viewWillAppear(Bool)
:
tabBarController.viewControllers?.forEach {
let _ = $0.view
$0.viewWillAppear(true)
}
Ignoring this causes views will be under navigation and tab bars.
来源:https://stackoverflow.com/questions/33261776/how-to-load-all-views-in-uitabbarcontroller