0

Consider the following navigation hierarchy:

NavigationContrller -> ViewController1 -> ViewController2

I'd like to detect when ViewController1 is presented by going from ViewController2, i.e. by pressing the "Back" button on the NavigationController.

The method I'm interested is - (void)viewWillAppear:(BOOL)animated. How can I check, whether the ViewController1 has been presented by going forward (i.e. NavigationController -> ViewController1) or by going backward (i.e. ViewController2 -> ViewController1)?

Richard Topchii
  • 7,075
  • 8
  • 48
  • 115
  • Check this question: https://stackoverflow.com/questions/44669562/detect-if-you-are-going-to-a-new-view-controller-or-previous. There's also an answer there that leads to this question: https://stackoverflow.com/questions/1816614/viewwilldisappear-determine-whether-view-controller-is-being-popped-or-is-showi/1816682#1816682, which is basically what you need. – Max Pevsner Apr 29 '19 at 13:51

2 Answers2

0

You can check the order of the controllers of your navigation stack in viewWillAppear like this:

      for controller in self.navigationController!.viewControllers as Array {
                //  print("controller \(controller) at i \(i)") 
      }
Letaief Achraf
  • 600
  • 1
  • 7
  • 14
0

You could use a Bool to keep track of the "push state":

class ViewController1: UIViewController {

    private var isBeingPushed = true

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        if isBeingPushed {
            print("forwards")
        } else {
            print("backwards")
        }
    }

    override func viewDidDisappear(_ animated: Bool) {
        isBeingPushed = false
        super.viewDidDisappear(animated)
    }

    override func didMove(toParent parent: UIViewController?) {
        if parent == nil {
            isBeingPushed = true
        }
        super.didMove(toParent: parent)
    }

}
André Slotta
  • 13,774
  • 2
  • 22
  • 34