Find out if user pressed the back button in uinavigationcontroller?

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
}

Leave a Comment