如何将方法添加到UINavigationbar后退按钮,所以每当我点击后退按钮时,我需要检查一些值并显示UIAlertView?这有什么选择吗?
我试过这种方法,但它为我工作
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
//show alert
}
以及这种方法,但两者都不是在讨论
-(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");
}
答案 0 :(得分:3)
是的,你可以 在viedDidLoad中
UIBarButtonItem * backBtn = [[UIBarButtonItem alloc]initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(goBackToAllPets:)];
self.navigationItem.leftBarButtonItem = backBtn;
编写以下函数来检查条件
-(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];
}
}
答案 1 :(得分:1)
假设您有两个控制器 - Controller1和Controller2。 从Controller1推送Controller2。所以在从Controller1推送ControllerController上的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方法中,您可以执行所需的检查。