Search code examples
uinavigationcontroller

Override back button in navigation stack while keeping appearance of default back button?


How do I override the back button for just one view (not for all the back buttons present in different views) such that on click of the back button, the root view controller is shown?


Solution

  • You need to replace the backbutton and associate an action handler:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        // change the back button to cancel and add an event handler
        UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@”back”
                                                                       style:UIBarButtonItemStyleBordered
                                                                      target:self
                                                                      action:@selector(handleBack:)];
    
        self.navigationItem.leftBarButtonItem = backButton;
    }
    
    - (void)handleBack:(id)sender {
        // pop to root view controller
        [self.navigationController popToRootViewControllerAnimated:YES];
    }