Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode: Detecting when a navigation controller implemented "back button" is pressed

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.

like image 470
Brandon A Avatar asked Sep 29 '22 20:09

Brandon A


1 Answers

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"); 
}
like image 133
Oleg Gordiichuk Avatar answered Oct 05 '22 06:10

Oleg Gordiichuk