iphone navigationController : 在退出当前视图之前等待 uialertview 响应

人气:181 发布:2022-10-16 标签: iphone objective-c uialertview uinavigationcontroller

问题描述

我有一个带有导航控制器管理的后退按钮的视图,我想检查当用户单击后退按钮时文件是否已保存.如果文件已保存,则返回上一个视图,否则 uialertview 会询问您是否要保存文件.

I have a view with a back button managed with a navigation controller and I want to check if a file has been saved when the user click on the back button. If the file has been saved you go back in the previous view, else a uialertview ask you if you want to save the file or not.

所以我这样做了,但视图消失了,之后出现了警报视图.

So I did that but the view disapear and the alertview appear after.

-(void)viewWillDisappear:(BOOL)animated {
if(!self.fileSaved){
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Save the file?"  delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes",nil];
    [alert show];
    [alert release];
}
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
switch (buttonIndex) {
    case 0:
        NSLog(@"NO");
        break;
    case 1:
        NSLog(@"yes");
        break;
    default:
        break;
}
}

推荐答案

调用viewWillDisappear的时候已经晚了.您应该更早地拦截后退按钮.我从未这样做过,但我的建议是在您的 viewDidAppear 方法中的 navigationBar 属性上设置委托:

When viewWillDisappear is called, it's already too late. You should intercept the back button earlier on. I have never done it, but my suggestion is to set the delegate on the navigationBar property in your viewDidAppear method:

// save the previous delegate (create an ivar for that)
prevNavigationBarDelegate = self.navigationController.navigationBar.delegate;

self.navigationController.navigationBar.delegate = self;

不要忘记在 viewWillDisappear 中重新设置它:

Don't forget to set it back in viewWillDisappear:

self.navigationController.navigationBar.delegate = prevNavigationBarDelegate;

然后拦截 shouldPopItem 方法:

Then intercept the shouldPopItem method:

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
     if(!self.fileSaved) {
         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Save the file?"  delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes",nil];
         [alert show];
         [alert release];

         return NO;
     }

   if ([prevNavigationBarDelegate respondsToSelector:@selector(navigationBar:shouldPopItem:)]) 
      return [prevNavigationBarDelegate navigationBar:navigationBar shouldPopItem:item];

   return YES; 
}

并在对话框的 YES 处理程序中,手动弹出控制器:

And in the YES handler for the dialog, manually pop the controller:

[self.navigationController popViewController:YES];

925