How to dismiss the Alert with click on outside of the alert in iOS?


Understanding and implementing UIAlert can be tricky especially if you’re new to iOS Development, In this post, we will be seeing how we can dismiss the alert when the user taps outside the alert box.

For this demo, we will be using UIAlert class, to configure alerts and action sheets with the message that you want to display and the actions from which to choose. After configuring the alert controller with the actions and style you want, present it using the present(_:animated: completion:) method. UIKit displays alerts and action sheets modally over your app's content.

You can read more about it: https://developer.apple.com/documentation/uikit/uialertcontroller

So let’s get started,

Step 1 − Open Xcode and create a single view application and name it UIAlertSample.

Step 2 − In Main. storyboard add one button, and create @IBAction and name it showAlert,

@IBAction func showAlert(_ sender: Any) { }

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.

Step 3 − Inside button action showAlert, First create UIAlert object as below

let uialert = UIAlertController(title: "WELCOME", message: "Welcome to my tutorials, tap outside to dismiss the alert", preferredStyle: .alert)

Step 4 − Present the alert and on its completion add a selector as shown below,

self.present(uialert, animated: true, completion:{
   uialert.view.superview?.isUserInteractionEnabled = true
   uialert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dismissOnTapOutside)))
})

Step 5 − Add selector function,

@objc func dismissOnTapOutside(){
   self.dismiss(animated: true, completion: nil)
}

Step 6 − Run the application,

import UIKit
class ViewController: UIViewController {
   override func viewDidLoad() {
      super.viewDidLoad()
   }
   @IBAction func showAlert(_ sender: Any) {
      let uialert = UIAlertController(title: "WELCOME", message: "Welcome to my tutorials, tap outside to dismiss the alert", preferredStyle: .alert)
      self.present(uialert, animated: true, completion:{
      uialert.view.superview?.isUserInteractionEnabled = true
      uialert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dismissOnTapOutside)))
      })
   }
   @objc func dismissOnTapOutside(){
      self.dismiss(animated: true, completion: nil)
   }
}

Updated on: 30-Aug-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements