5
votes

Scenario

I have an app with a navigation controller. When the navigation controller pushes another controller onto the stack, in the upper left corner of the screen it shows the back button "<(title of the last view controller)".

What I need

I need something like (pseudo code)...

-(void)detectedBackButtonWasPushed {

    NSLog(@"Back Button Pressed");

    //Do what I need done

}

Question

Because this button is created by the navigation controller and I did not create this button in storyboards, how do I get the back button 'hooked up' to a method like this?

examples of what Ive tried for Oleg

-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {

    UIViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"notification"];

    if (viewController == vc) {

        NSLog(@"BACK BUTTON PRESSED");
    }
}

Is this how I'm supposed to do it? Cause this doesn't work.

2

2 Answers

4
votes

Use viewWillDisappear to detect this.

-(void) viewWillDisappear:(BOOL)animated 
{ 
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) 
    { 
        [self backButtonPressed]; 
        [self.navigationController popViewControllerAnimated:NO]; 
    } 

    [super viewWillDisappear:animated]; 
} 

-(void)backButtonPressed 
{ 
   NSLog(@"YEA"); 
}
0
votes

Previously, I have solved this by setting the navigationBar leftItem to be a back button with a custom selector that dismisses the view along with whatever else it needed to do.

I might also suggest looking at the back button item and adding a target:self that is called on touch.