How to load all views in UITabBarController?

不想你离开。 提交于 2019-11-30 08:27:01

问题


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.


回答1:


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 }



回答2:


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




回答3:


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.




回答4:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!