Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

ios - How to instantiate and load a view controller before segueing to it using swift

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.7k users

...