How to dismiss UIAlertController when tap outside the UIAlertController?

leizh00701 picture leizh00701 · May 6, 2015 · Viewed 46.2k times · Source

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

chancyWu picture chancyWu · Apr 12, 2016

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)
}