1

is it possible to change the previous view controllers of a UINavigationController?

Suppose I have three view controllers (A, B, C) which are embedded in a UINavigationController. Tapping a button in A pushes to B and tapping a button in B will pushes to C. Now, if the user taps on the back button of C, I want redirect the user directly to A instead of B.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
Jay Patel
  • 343
  • 2
  • 19

4 Answers4

2
let arrViewControllers: [Any]? = self.navigationController?.viewControllers
    for controller: Any in arrViewControllers! {
        if (controller is cVC) {
            self.navigationController!.popToViewController(controller as! UIViewController, animated: true)
        }
    }
Nishant Bhindi
  • 2,242
  • 8
  • 21
1

Sure there is -

    self.navigationController?.popToViewController(viewControllerA, animated: true)

For more info, read the documentation.

Check out this SO question to learn how to combine it with the back button.

Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90
  • This also worked. To use this one i need to change back button to custom back button or change back button action. because if user swap to go back it will show second View Controller. – Jay Patel Sep 04 '17 at 11:47
1

You should remove B from your navigation controller's viewControllers array in C's viewDidAppear method.

var didRemoveB = false

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    if !didRemoveB {
        navigationController?.viewControllers.remove(atIndex: 1) //assuming B's index is 1
        didRemoveB = true
    }
}
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
0

It's possible in many way, First you can handle when your ViewController B is disappear and change stack of viewControllers in navigationController

override func viewWillDisappear(animated : Bool) {
    super.viewWillDisappear(animated)

    if (self.isMovingFromParentViewController()){
      self.navigationController.viewControllers = viewControllers // your viewControllers stack
    }
}

UPDATE

or pop to root:

self.navigationController.popToRootViewControllerAnimated()

or pop view controllers until the specified view controller is at the top of the navigation stack.:

self.navigationController.popToViewController(:animated:)
Yerken
  • 299
  • 1
  • 12