ios - Navigation between multiple NavigationControllers

后端 未结 2 509
孤城傲影
孤城傲影 2021-02-05 20:44

I\'m trying to understand a behavior of navigating between ViewControllers with (and without) using a NavigationController and I\'m misunderstanding some things while reading ar

2条回答
  •  猫巷女王i
    2021-02-05 21:21

    Imagine you have you standard application chain where you push / pop views in initial navigation controller. Then, imagine you have different view that is not part of that chain, like a user profile, which you present as modal view:

    Now the top navigation controller is initial so you start from here, while in order to use second one, you would have to access it through UIStoryboard like this (red arrow):

    // Get storyboard
    let storyboard = UIStoryboard(name: name, bundle: NSBundle.mainBundle())
    
    // Get profile NC
    let profileNC = storyboard.instantiateViewControllerWithIdentifier("LoginNC") as! UINavigationController
    

    But if you really want to present profile from one part of the app so it is not modal, you can do it as well (green arrow). The only difference is that now you don't need second navigation controller - so you don't connect push segue to red NC, but to login view controller directly. If you actually try to connect NC - NC and then run it, you will get runtime exception saying that you did it wrong.

    Memory

    All the VC stay in memory, no matter how you present them. This also holds true for background views when you present something as modal. If you have issues with memory due to long chains, you can implement cleaning / caching logic in your controllers:

    func viewWillAppear(animated: Bool) {
    
        // Call super first
        super.viewWillAppear(animated)
    
        // Prepare UI
    }
    
    func viewWillDisappear(animated: Bool) {
    
        // Call super first
        super.viewWillAppear(animated)
    
        // do some memory cleanup, since view will not be visible atm
    }
    

    Hope it helps!

提交回复
热议问题