leizh00701 leizh00701 - 3 months ago 164
iOS Question

How to dismiss UIAlertController when tap outside the UIAlertController?

How to dismiss

UIAlertController
when tap outside the
UIAlertController
?

I can add a
UIAlertAction
of style
UIAlertActionStyleCancel
to dismiss the
UIAlertController
.

But I want to add the function that when user tap outside the
UIAlertController
the
UIAlertController
will dismiss. How to do that? Thank you.

Answer

Add a separate cancel action with style UIAlertActionStyleCancel. So that when user taps outside, you would get the callback.

 UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert Title" message:@"A Message" preferredStyle:UIAlertControllerStyleActionSheet];


 [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
 // Called when user taps outside
    }]];

--