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

半城伤御伤魂 提交于 2019-12-01 11:04:18

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