且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 iOS 中离开视图之前要求用户确认

更新时间:2023-12-01 20:27:34

当 viewWillDissapear 不起作用时显示警报视图,因为视图已经消失,它正在被删除.

Showing the alert view when viewWillDissapear won't work, because the view is already dissapearing, it's on its way to be removed.

您可以做的是在按下后退按钮时为自己添加一个自定义操作,然后您决定按下后退按钮时要执行的操作,您可以显示警报视图,然后在其中一个按钮中进行关闭视图,如下所示:

What you can do, is add yourself a custom action when the back button is pressed, then you decide what to do when the back button is pressed, you can show the alert view, and then in one of the buttons procedd to dismiss the view, something like this:

- (id)init {
    if (self = [super init]) {
    self.navigationItem.backBarButtonItem.target = self;
    self.navigationItem.backBarButtonItem.action = @selector(backButtonPressed:);
  }
    return self;
}

然后在按下后退按钮时显示警报视图:

Then show the alert view when the back button is pressed:

-(void)backButtonPressed:(id)sender
 {
     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Exit", @"") message:NSLocalizedString(@"Are you sure you want to leave? Changes will be discarded", @"") delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", @"") otherButtonTitles:NSLocalizedString(@"Accept", @""), nil];      
    [alertView show];           
}

现在,当按下警报视图中的确认按钮时,只需调用:

Now, when the confirmation button in the alert view is pressed, just call:

[self.navigationController popViewControllerAnimated:YES];

如果用户取消或者什么都不做

Or do nothing if the user cancels