添加方法到UINavigationBar后退button?
我如何添加方法到UINavigationbar后退button,所以每当我点击后退button,我需要检查一些值,并显示UIAlertView? 有没有这个选项?
我尝试了这种方法,但它为我工作
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated { //show alert }
而且这种方法,但都不是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"); }
是的,你可以在viedDidLoad
UIBarButtonItem * backBtn = [[UIBarButtonItem alloc]initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(goBackToAllPets:)]; self.navigationItem.leftBarButtonItem = backBtn;
写下面的function来检查情况
-(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]; } }
假设你有两个控制器 – Controller1和Controller2。 Controller2从Controller1被推送。 所以在从Controller1导航控制器上推Controller2之前
Controller2 *controller2 = [[[Controller2 alloc] init]autorelease]; self.navigationItem.hidesBackButton = YES;
现在,在Controller2的viewDidLoad:方法中,添加以下片段
UIBarButtonItem *backBarButtonItem =[[[UIBarButtonItem alloc]initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(goBackToAllPets:)]autorelease]; self.navigationItem.leftBarButtonItem = backBarButtonItem;
并在backButtonClicked方法中,您可以执行您想要的检查。