Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
806 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...