Add method to UINavigationBar back button?

2019-03-02 02:23发布

How can i add method to UINavigationbar back button, so whenever I click that back button I need to check some values and show UIAlertView? Is there any option for this?

i tried this method but its working for me

  - (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated 
    {
    //show alert 
    }

and also this method but both are not woking

-(void) viewWillDisappear:(BOOL)animated {
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
        // back button was pressed.  We know this is true because self is no longer
        // in the navigation stack.
         NSLog(@"hi");
    }

2条回答
地球回转人心会变
2楼-- · 2019-03-02 02:37

Suppose you have two controllers - Controller1 and Controller2. Controller2 is pushed from Controller1. So before pushing the Controller2 on the navigationController from Controller1

Controller2 *controller2 = [[[Controller2 alloc]  init]autorelease];
self.navigationItem.hidesBackButton = YES;   

Now, in the viewDidLoad: method of Controller2, add the following snippet

UIBarButtonItem *backBarButtonItem =[[[UIBarButtonItem alloc]initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(goBackToAllPets:)]autorelease];
self.navigationItem.leftBarButtonItem = backBarButtonItem;

and in the backButtonClicked method, you can perform the checks you want to.

查看更多
我只想做你的唯一
3楼-- · 2019-03-02 02:48

Yes you can In viedDidLoad

UIBarButtonItem * backBtn = [[UIBarButtonItem alloc]initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(goBackToAllPets:)];

    self.navigationItem.leftBarButtonItem = backBtn;

write following function to check condition

-(void)goBackToAllPets:(id)sender
{
    if(/*check condition*/)
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"message" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
        alert.tag = 0;
        [alert show];


    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }


}
查看更多
登录 后发表回答