1
votes
static func showMenuView(parentVC:UIViewController){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let resultController = storyboard.instantiateViewController(withIdentifier: "menuViewController") as? MenuViewController;
    let segue:DragDownSettingSegue = DragDownSettingSegue.init(identifier: "", source: parentVC, destination: resultController);
    parentVC.prepare(for: segue, sender: nil);
    segue.perform();
}

I am programmatically segueing the viewcontrollers. ViewController A to B, and then B to C, and then C to D, an then D to B. There is a button "Back" in B. So i want to go to A when i go back from B. so for this, when D to B then i want to clear all the view viewcontroller from stack instead of A and B. Issues: I can't get the list of stacked view-controllers.

3
Have you embedded the first view controller i.e. A in a navigation controller? What is the segue type you are using? - PGDev

3 Answers

0
votes

UINavigationController holds its view controllers in a navigationController.viewControllers The property, which is an array.

let viewControllers = navigationController.viewControllers
print(viewControllers)

You can inspect that value to see the navigation stack.

0
votes

You can get the array of viewcontrollers using

let viewControllers: [UIViewController] = self.navigationController!.viewControllers

Then you can pop to a specific viewcontroller by using popToViewController function. For example

self.navigationController!.popToViewController(viewControllers[2], animated: true)
0
votes

Use unwind segue :)

You don't need to clear the viewController's stack manually. Drag a unwind segue from B to A. Thats all u need :)

EDIT:

I believe you have confused the concept of UnwindSegue. Unwind segue is not just way to hop from one view controller to another. When you perform the Unwind segue from ViewController B to View Controller A, not just the ViewController A will be loaded but all the intermediary ViewControllers pushed in between will be de allocated as well.

Here is the proof :)

My ViewController A's ViewwillAppear

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    print(self.navigationController?.viewControllers.count ?? 0)
}

My ViewController A's unwind segue

@IBAction func unwindToA(segue: UIStoryboardSegue) {
    //perform whatever u have to do before unwind segue completes 
}

Here is my flow.

VCA -pushes-> VCB -pushes-> VCC

I then do unwind segue from VCC to VCA. So as expected on performing unwindSegue VCA's viewWillAppear gets called. And as expected the navigationController's viewController count is 1. Which is my VCA. So obviously VCB was deallocated along with VCC.

You can write dealloc/deinit to confirm the deallocation :)

Finally never mess with NavigationController's ViewController stack manually when u can achieve the same with proper constructs like segue and unwind segue and popToRootViewController like methods.

Hope it helps