How to test if a Navigation Controller’s Back Button was pressed

Screen Shot 2015-11-10 at 11.33.31

Sometimes it’s helpful to know if the Back Button on a UINavigationController was pressed. For example, an app that has a Save button on the left could double-up the Back Button as a way to cancel the operation.

Since iOS 5 there’s a view controller property that we can check in viewWillDisappear: if isMovingFromParentViewController returns YES, the current view controller is about to be popped off the stack.

Call the following method in the view controller that’s currently on the navigation stack, and being presented by the navigation controller:

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // check if the back button was pressed
    if (self.isMovingFromParentViewController) {

        // do something here if that's the case
        NSLog(@"Back button was pressed.");

viewWillDisappear is called whenever our view controller is about to be dismissed, either by the navigation controller, or modally. We may not want anything to happen when the dismissal happens while this view controller was presented modally, so this check makes sure we only opt-in to the navigation controller’s Back Button presses.

Note that the property is only available inside the viewWillAppear and viewWillDisappear methods.

Leave a Reply