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.
Step 1 − Open Xcode and create a single view application and name it UIAlertSample. So basically, when we tap on the button an alert will be displayed, when the user taps outside the alert the alert will be dismissing.
1. From the Alerts tab, under Alerts, click Inbox. 2. On the Alerts Inbox page, click the check boxes in front of the alerts you want to dismiss, then click the Dismiss button.
You can dismiss the alert by calling dismissViewControllerAnimated method on alertController object.
Add a separate cancel action with style UIAlertActionStyleCancel
. So that when user taps outside, you would get the callback.
Obj-c
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 }]];
Swift 5.0
let alertController = UIAlertController(title: "Alert Title", message: "A Message", preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in // Called when user taps outside }))
If you are targeting devices having iOS > 9.3 and using Swift and preferredStyle is Alert you can use snippet as below:
func showAlertBtnClicked(sender: UIButton) { let alert = UIAlertController(title: "This is title", message: "This is message", preferredStyle: .Alert) self.presentViewController(alert, animated: true, completion:{ alert.view.superview?.userInteractionEnabled = true alert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertControllerBackgroundTapped))) }) } func alertControllerBackgroundTapped() { self.dismissViewControllerAnimated(true, completion: nil) }
With swift 3:
func showAlertBtnClicked(sender: UIButton) { let alert = UIAlertController(title: "This is title", message: "This is message", preferredStyle: .alert) self.present(alert, animated: true) { alert.view.superview?.isUserInteractionEnabled = true alert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertControllerBackgroundTapped))) } } func alertControllerBackgroundTapped() { self.dismiss(animated: true, completion: nil) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With