问题
I have an issue when I go from viewController A to viewController B, in which it has roughly a 5 second delay before segueing to it. I believe it is due to the amount of views that I'm loading up in viewDidLoad.
I have an xib file that has a stack view of 11 sections that represent levels. Each section has a button and a few images that can change depending on the users progress.
In addition, I instantiate 10 of these xib views to load in a scrollview. This all happens in the viewDidLoad.
I'm wondering if I can load viewController B and have it all ready to go before actually clicking the button that segue's to it; hopefully fixing the delay I get. I'm also using custom segues to and from controllers.
Any help I can get is appreciated. I have looked into this myself, but most topics that I find are outdated, or don't apply. Thanks again for any pointers.
UPDATE: the answer does answer a portion of my question as far as how to prep a view controller for efficiency purposes, it doesn't answer the delay part, but I think I figured it out if you read the comments below answer...
回答1:
You can move all the heavy code out of viewDidLoad()
into some custom method
func prepare() {
// Something hard
}
than you can prepare your controller at anytime and store it
var heavyController: HeavyViewController?
override func viewDidLoad() {
super.viewDidLoad()
heavyController = HeavyViewController()
heavyController?.prepare()
}
than just use heavyController in segue instead of creating new one. Hope this helps.
P.S. consider moving heavy parts of code into background thread, you can check the example.
UPDATE: To show your prepared controller using segue do something like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "HeavyController" {
present(heavyController, animated: true, completion: nil)
}
}
来源:https://stackoverflow.com/questions/42188607/how-to-instantiate-and-load-a-view-controller-before-segueing-to-it-using-swift