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.
If you are using Swift :
Add an action with
addAction(_:)
andstyle:UIAlertActionStyle.Cancel
.The `handler will be called when ou tap on the button or outside the frame.
Objective-C :
Swift, Xcode 9
Dismiss AlertController with cancel button
provide action to your alertController where
UIAlertAction
's style is.cancel
if you don't want user to dismiss alertController after touch up outside of alertController, disable user interaction of first subviews of alertController in completion closure of present method.
Dismiss AlertController on touchup outside of Controller view
If you don't want cancel button in your controller view and want to dismiss controller when user touchup outside of controller view, do so
Swift 4:
Dismiss Action Sheet when User Taps outside Action Sheet created using UIAlertController
Code Snippet:
The simplest way:
The easiest way in Obj-C:
and then:
If you are targeting devices having iOS > 9.3 and using Swift and preferredStyle is Alert you can use snippet as below:
With swift 3: