Search code examples
iosuinavigationitembackbarbuttonitem

hidesBackButton works but backbarbuttonitem setAction not working


I'd like to change action of my backbutton in one of my ViewController. Instead of going back to the precedent view, I want to perform an action in the same ViewController.

self.navigationItem.hidesBackButton=NO;

hides the BackButton but

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

and

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

do the same as before (going back to precedent ViewController). Nothing changes.

-(void)performBackNav:(id)sender {
//Actions
[self.navigationController popViewControllerAnimated:NO];
}

Any ideas to modify backbarbuttonitem's action ?


Solution

  • Instead of overriding the action method of default back button create a custom button. this is one of the way Try this

    {
        UIButton *urButton = [UIButton buttonWithType:UIButtonTypeCustom];
        urButton.frame = urRequiredFrame;
        [urButton setImage:urImage forState:UIControlStateNormal];
        [urButton addTarget:self action:@selector(performBackNav:)
             forControlEvents:UIControlEventTouchUpInside];
    
        UIBarButtonItem *doneButton =[[UIBarButtonItem alloc] initWithCustomView:urButton];
        self.navigationItem.leftBarButtonItem=doneButton;
    }
    
    
    -(void)performBackNav:(id)sender {
    //Actions
    [self.navigationController popViewControllerAnimated:NO];
    }