在iOS中按“后退”button时如何创build确认popup窗口?
我想添加一个popup,当有人推我的iOS应用程序的“后退”button,要求用户,如果他真的想回来。 然后,根据用户的反应,我想撤消该操作或继续。 我已经尝试在View的ViewWillDisappear函数中添加代码,然后编写适当的代理,但是它不起作用,因为它总是改变视图,然后显示popup窗口。 我的代码是:
-(void) viewWillDisappear:(BOOL)animated { _animated = animated; if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) { UIAlertView *alert_undo = [[UIAlertView alloc] initWithTitle:@"UIAlertView" message:@"You could be loosing information with this action. Do you want to proceed?" delegate:self cancelButtonTitle:@"Go back" otherButtonTitles:@"Yes", nil]; [alert_undo show]; } else [super viewWillDisappear:animated]; }
代表实现是:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { NSString *title = [alertView buttonTitleAtIndex:buttonIndex]; if([title isEqualToString:@"Yes"]) { [super viewWillDisappear:_animated]; } }
这根本不起作用。 现在有人有更好的方法去做,或者有什么可能是错的?
非常感谢你,
一旦 – -viewWillDisappear:
被调用,没有停止你的viewController
消失。
理想情况下,应该覆盖navigationBar
栏的后退button,并在其中的方法,显示警报( 其余的几乎相同 )
- (void)viewDidLoad { //... UIBarButtonItem *bbtnBack = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(goBack:)]; [self.navigationItem setBackBarButtonItem: bbtnBack]; } - (void)goBack:(UIBarButtonItem *)sender { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"...Do you want to proceed?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil]; [alert show]; } - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { switch(buttonIndex) { case 0: //"No" pressed //do something? break; case 1: //"Yes" pressed //here you pop the viewController [self.navigationController popViewControllerAnimated:YES]; break; } }
注意 :不要忘记在这个viewController
的.h文件中声明<UIAlertViewDelegate>
感谢您的回答,@staticVoidMan! 我终于用一些修改你的代码。 后退button不能修改,所以应该创build一个额外的button,隐藏标准的button。 唯一的问题是新的“后退”button的风格,这不等于标准的风格。 最终的代码是:
- (void)viewDidLoad { self.navigationItem.hidesBackButton = YES; UIBarButtonItem *bbtnBack = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(goBack:)]; self.navigationItem.leftBarButtonItem = bbtnBack; } - (void)goBack:(UIBarButtonItem *)sender { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"...Do you want to proceed?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil]; [alert show]; } - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { switch(buttonIndex) { case 0: //"No" pressed //do something? break; case 1: //"Yes" pressed //here you pop the viewController [self.navigationController popViewControllerAnimated:YES]; break; } }