AppsDev AppsDev - 3 months ago 19
iOS Question

Trying to handle "back" navigation button action in iOS

I need to detect when the user taps the "back" button on the navigation bar, in order to perform some operations when that occurs. I'm trying to set manually an action to such button, this way:

[self.navigationItem.backBarButtonItem setAction:@selector(performBackNavigation:)];

- (void)performBackNavigation:(id)sender
// Do operations

[self.navigationController popViewControllerAnimated:NO];

I firstly placed that code in the view controller itself, but I found that
seemed to be
, so I moved that same code to the parent view controller, which pushes the former to the navigation stack. But I'm neither able to make it work. I've read some posts regarding this issue, and some of them said that the selector needs to be set at the parent view controller, but for me it doesn't work anyway... What could I'm doing wrong?



Try this code using VIewWillDisappear method to detect the press of The back button of NavigationItem:

-(void) viewWillDisappear:(BOOL)animated {
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
       // Navigation button was pressed. Do some stuff 
      [self.navigationController popViewControllerAnimated:NO];
    [super viewWillDisappear:animated];

OR There is another way to get Action of the Navigation BAck button.

Create Custom button for UINavigationItem of back button .

For Ex:

In ViewDidLoad :

    - (void)viewDidLoad {
        [super viewDidLoad];
        UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonItemStyleBordered target:self action:@selector(home:)];

    -(void)home:(UIBarButtonItem *)sender {
           [self.navigationController popToRootViewControllerAnimated:YES];

Swift :

override func willMoveToParentViewController(parent: UIViewController?) {
    if parent == nil {
        // Back btn Event handler