68

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

3
  • 2
    Do you want to to know whether it was a user initiated popping or popping in general? May 23, 2011 at 1:20
  • It might be good to elaborate on your overall goal. There might be an easier way to do what you're trying to do. If you need to know whether some value was changed or set in the second view, for instance, you should simply check that value.
    – jscs
    May 23, 2011 at 1:53
  • Popping is what i want to be told about.
    – Andrew
    May 23, 2011 at 2:01

7 Answers 7

110

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
}
5
  • This works great! But you mentioned pre-iOS 5.0.. Is there an iOS 5 specific method that can be used to catch the back button callback?
    – Keller
    Aug 14, 2012 at 21:21
  • 4
    This gets also gets called when the VC is pushed (at least on iOS 6).
    – fabian789
    Jan 19, 2013 at 7:20
  • Hey, viewDidDisappear did not get called in iOS 4.3 for me. While both methods are called for me in iOS 5. Any thoughts?
    – NightFury
    Apr 30, 2013 at 10:22
  • 2
    didMoveToParentViewController; is not a good solution, it will also be call when this view is appear.
    – 蘇健豪
    Jan 21, 2015 at 8:42
  • 2
    You need to check if the parent is nil in order to determine if the view was added or removed.
    – Andrew
    Nov 6, 2015 at 1:53
81

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

4
  • missing parenthesis in the if statement, but otherwise very helpful answer. thanks!
    – AddisDev
    Jan 7, 2014 at 22:43
  • 2
    As an alternative to this, inspired by Andrew's answer, you can do something before the move by overriding willMoveToParentViewController: instead of didMoveToParentViewController:.
    – fatuhoku
    Mar 31, 2014 at 13:09
  • 1
    Way better method than programming your custom button. Thanks. Oct 14, 2015 at 21:24
  • 1
    it doesn't mean exactly if user presses back button. There are tons of other cases when it's triggered
    – Injectios
    Nov 21, 2016 at 15:52
7

UINavigationController has a delegate property that issues delegate callbacks. Please see the iOS reference here.

The delegate doesn't have a "back button pressed" callback, but instead it tells you when something is going to appear on the navigation stack. When you press back, you are "popping" the top view controller off the stack, so it will tell you that the view is about to appear. I think this is the callback you'd be looking for.

You could have some simple logic to check if it's the view controller that's "interested", and then you could send a notification, et al.

3
  • 1
    There is no delegate that shows when a uinavigationcontroller has popped off the stack
    – Andrew
    May 23, 2011 at 1:43
  • I said that UINavigationController has a delegate. If UINavigationController is managing your view hierarchy, it indeed will callback to the delegate, if set.
    – makdad
    May 23, 2011 at 22:34
  • I am trying to do this. When backing up, unfortunately, it calls the "new" view controller [the one being backed up to] -viewWillAppear before the delegate method -navigationController:willShowViewContoller:animated: is called for that same viewController...
    – chadbag
    Apr 21, 2013 at 0:03
5

For the sake of completeness, mix of two most upvoted answers (1, 2) in Swift:

override func willMoveToParentViewController(parent: UIViewController?) {
    super.willMoveToParentViewController(parent)
    if parent == nil {
        // view controller is popping
    }
}
1
  • 4
    Don't use will, use did since there's screen edge pop gesture. Oct 14, 2017 at 21:37
2

This is a slightly different scenario, but I thought the solution might help others out.

In my situation, I had a UINavigationController within a UIPopoverController. I needed to detect whether the user clicked the back button, or clicked outside of the popover. To do this I checked the visibleViewController property in viewWillDisappear. If the view controller is still the visibleViewController when closing, then the popover is being closed by another means. If the view controller is not the visibleViewController when closing, then the back button was pressed.

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

    if (self.navigationController.visibleViewController != self) {
        <Do something since we're closing using something else>
    } else {
        <Do something since we're closing because of the back button>
    }
}

I tried using zach's solution, but isMovingFromParentViewController returns true for both cases.

I verified this works in iOS 5+

I hope this helps.

2

Create a custom back bar button and set the target,

Step 1: Add these methods to your class

- (void)backButtonClicked :(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addBackBarButton{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 55, 35);
    [button setTitle:@"back" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = customBarItem;
}

Step 2: Call [self addBackBarButton]; in viewDiDLoad method

You will get the action in backButtonClicked method. You can play around with it the way you want.

Cheers!

-11

The only way to do this so you know for sure that it was the back button is to create a custom button. If you don't know how to do that, check out this tutorial. It won't look exactly like the normal back button, but close. If you need more help, post a comment

4
  • 1
    Check andrews other answer, and if the poster reads this perhaps accept that as the correct answer May 14, 2013 at 11:43
  • @user461864, you mean the other Andrew, not Andrew's other answer--they're different Andrews. But you are right, the other answer is far superior; the present one is a lot of extra work by comparison.
    – JohnK
    Jun 2, 2013 at 1:20
  • Damn you are right,.. I thought it was weird that he answered twice but that explains Jun 19, 2013 at 20:40
  • 14
    This answer is incorrect and should be removed by the poster.
    – gchbib
    Mar 20, 2014 at 12:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.