Find out if user pressed the back button in uinavigationcontroller?

When a view loads, i want to see if it's because the user pressed the back button. How can i check this?


Solution 1:

The best solution I've found to detect a UINavigationController's back button press (pre-iOS 5.0) is by verifying that the current view controller is not present in the in the navigation controller's view controller stack.

It is possibly safer to check this condition in - (void)viewDidDisappear:(BOOL)animated as logically, by the time that method is called it would be extremely likely that the view controller was removed from the stack.

Pre-iOS 5.0:

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    if (![[self.navigationController viewControllers] containsObject:self]) {
        // We were removed from the navigation controller's view controller stack
        // thus, we can infer that the back button was pressed
    }
}

iOS 5.0+ you can use -didMoveToParentViewController:

- (void)didMoveToParentViewController:(UIViewController *)parent
{
    // parent is nil if this view controller was removed
}

Solution 2:

in your viewWillDisappear method check

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    if ([self isMovingFromParentViewController]) {
      //specific stuff for being popped off stack
    }
}

This is only for post iOS 5