Swift, Xcode 9
Dismiss AlertController with cancel button
provide action to your alertController where UIAlertAction
's style is .cancel
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
Using this method alertController will be dismissed when user will tap to cancel action button as well as outside of the alertController.
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.
self.present(alertController, animated: true) {
alertController.view.superview?.subviews[0].isUserInteractionEnabled = false
}
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
self.present(alertController, animated: true) {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissAlertController))
alertController.view.superview?.subviews[0].addGestureRecognizer(tapGesture)
}
@objc func dismissAlertController(){
self.dismiss(animated: true, completion: nil)
}