3

I need to check if the back button is pressed in Swift. The action does not fire programmatically, so the approach appears to be to check if self is in the viewcontroller stack. I think the solution is here:

How to check for self with contains() in Swift?

However for each of the answers Swift tells me that contains is an unresolved identifier. I understand that is it in the Swift standard library so I assume I don't know how to use it.

Therefore what is the proper form of the following function?

override func viewDidDisappear(_ animated: Bool) {
    if let viewControllers = self.navigationController?.viewControllers as? [UIViewController] {
        if (contains(viewControllers, self)) {
            print("Back button not pressed")
        } else {
                print ("Back button pressed")
        }
    }
}
stevenpcurtis
  • 1,907
  • 3
  • 21
  • 47

1 Answers1

3

Similar to RAJAMOHAN-S I look at where I'm transitioning from. However, the function

override func willMove(toParentViewController parent: UIViewController?)

provides a nice way of doing that; I combined with a simple bool variable to differentiate if the back button was really used or whether another programmatic method meant a transition event.

override func willMove(toParentViewController parent: UIViewController?) {
    super.willMove(toParentViewController: parent)
    if parent == nil {
        // The back button was pressed, can be acted on 
        }
    }
    else{
        print ("Coming here from a child view")
    }
}
stevenpcurtis
  • 1,907
  • 3
  • 21
  • 47