Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load all views in UITabBarController?

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.

like image 311
Sam Avatar asked Oct 21 '15 14:10

Sam


2 Answers

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 }
like image 99
Robert Avatar answered Oct 09 '22 13:10

Robert


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...

like image 26
JRafaelM Avatar answered Oct 09 '22 12:10

JRafaelM