确认UINavigationController上的后退按钮

mtm*_*ock 12 back-button uinavigationcontroller ios

我正在使用我正在使用的storyboard应用程序UINavigationController.我想在默认的后退按钮中添加一个确认对话框,这样用户就不会意外注销.有办法做到这一点吗?我发现,当它被自动创建时,我不能简单地访问后退按钮UINavigationController.

有任何想法吗?

XJo*_*nes 22

不幸的是,你不能以这种方式拦截后退按钮.最接近的传真是使用您自己的UIBarButtonItem设置navigationItem.leftBarButtonItem并设置动作以显示您的警报等.我有一个图形设计师创建看起来像标准后退按钮的按钮图像.

另外,我需要拦截后退按钮的原因不同.我敦促你重新考虑这个设计选择.如果您要呈现用户可以进行更改的视图,并且您希望他们可以选择保存或取消IMHO,则最好使用"保存"和"取消"按钮与带警报的后退按钮.警报通常很烦人.或者,明确表示用户所做的更改是在他们创建时提交的.那么这个问题没有实际意义.

  • 你仍然可以在故事板中添加一个`leftBarButtonItem`并对其进行配置.它将取代后退按钮. (2认同)
  • @XJones你的答案更好.我用UIBarButtonSystemItemCancel替换了后退按钮,我手动弹出.我还添加了一个UIBarButtonSystemItemSave作为rightBarButtonItem.这是取消/替换后退按钮最干净的解决方案. (2认同)

Tho*_*est 10

我如何工作围绕这种情况是通过设置leftBarButtonItemUIBarButtonSystemItemTrash风格(使它立即明显的是,他们会删除该项目草案),并添加确认删除的警报视图.因为你设置了一个自定义leftBarButtonItem它不会像一个后退按钮,所以它不会自动弹出视图!

在代码中:

- (void)viewDidLoad
{
    // set the left bar button to a nice trash can
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash
                                                                                          target:self
                                                                                          action:@selector(confirmCancel)];
    [super viewDidLoad];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex)
    {
        // The didn't press "no", so pop that view!
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)confirmCancel
{
    // Do whatever confirmation logic you want here, the example is a simple alert view
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning"
                                                    message:@"Are you sure you want to delete your draft? This operation cannot be undone."
                                                   delegate:self
                                          cancelButtonTitle:@"No"
                                          otherButtonTitles:@"Yes", nil];
    [alert show];
}
Run Code Online (Sandbox Code Playgroud)

这真的很简单!我没有看到重大问题,tbh:p

不过,我必须添加免责声明; 这样做会破坏默认的导航行为,苹果可能不喜欢开发人员这样做.我还没有提交任何具有此功能的应用程序,因此我不确定Apple在执行此操作时是否会在商店中允许您的应用程序,但请注意;)

更新:好消息,大家好!与此同时,我已经向App Store 发布了一个应用程序(Appcident),这种行为已经到位,Apple似乎并不介意.