Confirm back button on UINavigationController

前端 未结 7 1846
南旧
南旧 2020-12-09 18:03

I am using the storyboard for my app which is using UINavigationController. I would like to add a confirmation dialog to the default back button so

7条回答
  •  时光取名叫无心
    2020-12-09 18:32

    How I worked around this situation is by setting the leftBarButtonItem to the UIBarButtonSystemItemTrash style (making it instantly obvious that they'll delete the draft item) and adding an alert view confirming the deletion. Because you set a custom leftBarButtonItem it won't behave like a back button, so it won't automatically pop the view!

    In code:

    - (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];
    }
    

    It's really as simple as that! I don't see the big issue, tbh :p

    I have to add a disclaimer, though; doing this breaks the default navigation behaviour and apple might not like developers doing this. I haven't submitted any apps (yet) with this feature, so I'm not sure if apple will allow your app in the store when doing this, but be warned ;)

    UPDATE: Good news, everybody! In the meanwhile I've released an app (Appcident) to the App Store with this behavior in place and Apple doesn't seem to mind.

提交回复
热议问题