UIAlertController handle dismiss upon click outside (IPad)

Tomer Peled picture Tomer Peled · Aug 23, 2014 · Viewed 18.4k times · Source

Previous to iOS8 we used the UIActionSheet for showing alert and now we need to use the UIAlertController.

When we used the UIActionSheet we could easily handle situations where the user clicked outside the pop up (which means he want to cancel the operation) by comparing the clickedButtonAtIndex to the cancelButtonIndex - if the user indeed pressed outside the popup we got the cancel button index in this function.

How can we handle these situations with the new UIAlertController? I tried to use the "completion" block but it doesn't have any context. Is there an easy way to handle this? (other than "saving" the actions states in some general variable).

Answer

Gareth picture Gareth · Aug 24, 2014

You can add an action with style:UIAlertActionStyleCancel and the handler for this action is called when the user taps outside the popup.

if ([UIAlertController class]) {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert Title" message:@"A Message" preferredStyle:UIAlertControllerStyleActionSheet];

    [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        NSLog(@"User clicked button called %@ or tapped elsewhere",action.title);
    }]];

    [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSLog(@"User clicked button called %@",action.title);
    }]];

    [alertController addAction:[UIAlertAction actionWithTitle:@"Other" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        NSLog(@"User clicked button called %@",action.title);
    }]];

    UIControl *aControl = (UIControl *) sender;
    CGRect frameInView = [aControl convertRect:aControl.bounds toView:self.view];
    alertController.popoverPresentationController.sourceRect = frameInView;
    alertController.popoverPresentationController.sourceView = self.view;
    alertController.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
    [self presentViewController:alertController animated:YES completion:nil];
}