6

Is it possible to check when the back button is pressed in a UINavigationController stack? I've tried adding a action and target to self.navigationItem.backBarButtonItem to no avail.

Anyone have any solutions?

  • 1
    When you change the backBarButtonItem, make sure you are changing it on the controller that you are going back /to/, not the one that was just pushed. Also, you can only set a custom title or a custom view. If you set a custom image, it has no effect. Finally, you can use Noah's suggestion below, but make yourself the delegate of the navigation controller itself, and respond to the didPopViewController: family of methods. – Jason Coco Mar 30 '10 at 00:25
  • 1
    UINavigationControllerDelegate doesn't have will/didPopViewController methods, only will/didShowViewController. – dstnbrkr Apr 03 '10 at 02:41

2 Answers2

0

You can try my way:

Write in your ViewController:

UIBarButtonItem *backBt = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"imageNameOfBackButton"] style:UIBarButtonItemStyleBordered target:self action:@selector(backBt_touch:)];
self.navigationItem.leftBarButtonItem = backBt;

And action method:

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

You have to take a photo of back button you want.

Animation of hiding back button when viewController is popped is not the same animation of iOS!

P/s: enter image description here I've get it from simulator. Hope it useful! :)

Tony
  • 4,311
  • 26
  • 49
-1

One way to get at this would be to override viewWillDisappear in the UIViewController that is visible when the back button is pressed:

- (void)viewWillDisappear:(BOOL)animated {
    if (self.isMovingFromParentViewController) {
        // handle back button press
    }
}

Obviously this doesn't directly intercept the press on the back button itself, but it gives you a chance to perform logic at that time.

mon4goos
  • 1,569
  • 13
  • 24
  • This's a idea but... `viewWillDisappear` will be called in too many case. This is not perfect way! – Tony May 24 '13 at 08:43
  • I could be missing something, but I think checking for `self.isMovingFromParentViewController` solves that problem. – mon4goos May 24 '13 at 14:07
  • @mon4goos the self.isMovingFromParentViewController doesn't work – Dejell Dec 10 '13 at 09:23
  • Well it does work, and it is better than using `self.navigationItem.leftBarButtonItem` which shows no back arrow. This answer got demoted for no reason. – bio Aug 24 '16 at 17:26