2

I have 4 view controllers suppose A,B,C,D. ViewController D is on top and on click of button I have to go to ViewController A and remove all remaining ViewControllers. How to achieve this

Ragini
  • 332
  • 1
  • 4
  • 16

3 Answers3

3
self.navigationController.popToRootViewController(animated: true)
Retterdesdialogs
  • 3,180
  • 1
  • 21
  • 42
3

The UINavigationController's viewControllers property is get set property, that means you could write your own array of view controllers.

example,

let VCs = self.navigationController.viewControllers    //VCs = [A, B, C, D]

let vcA  = VCs[0]    //vcA = A
//finally
self.navigationController.viewControllers = [vcA] //done
// OR
self.navigationController.setViewControllers([vcA], animated: true)
Shubham Naik
  • 410
  • 1
  • 7
  • 18
0

If you are looking for one viewController in the stack. I have also added the code for if you couldn't find that one controller in the stack goto mainController or the firstController in the stack:

if let viewControllers = self.navigationController?.viewControllers {
    var element_count = 0
    for controller in viewControllers {
        if controller is YourViewController {
            element_count = 1
            self.navigationController?.popToViewController(controller, animated: true)
            break
        }
    }
    if element_count != 1{
        _ = self.navigationController?.popToRootViewController(animated: true)
    }
}
Prateekro
  • 566
  • 1
  • 6
  • 28