Making an Alert in iOS
This is a repost of an answer I wrote on Stack Overflow.
Alerts are useful for displaying a message to a user and optionally giving them a chance to respond to it. In iOS you us a UIAlertController
to do that. This is the equivalent of an Android AlertDialog (or a Flutter AlertDialog). The examples below show a basic setup for one, two, and three buttons.
One Button

class ViewController: UIViewController { @IBAction func showAlertButtonTapped(_ sender: UIButton) { // create the alert
let alert = UIAlertController(title: "My Title", message: "This is my message.", preferredStyle: UIAlertController.Style.alert) // add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)) // show the alert
self.present(alert, animated: true, completion: nil)
}
}
Two Buttons

class ViewController: UIViewController { @IBAction func showAlertButtonTapped(_ sender: UIButton) { // create the alert
let alert = UIAlertController(title: "UIAlertController", message: "Would you like to continue learning how to use iOS alerts?", preferredStyle: UIAlertController.Style.alert) // add the actions (buttons)
alert.addAction(UIAlertAction(title: "Continue", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil)) // show the alert
self.present(alert, animated: true, completion: nil)
}
}
Three Buttons

class ViewController: UIViewController { @IBAction func showAlertButtonTapped(_ sender: UIButton) { // create the alert
let alert = UIAlertController(title: "Notice", message: "Lauching this missile will destroy the entire universe. Is this what you intended to do?", preferredStyle: UIAlertController.Style.alert) // add the actions (buttons)
alert.addAction(UIAlertAction(title: "Remind Me Tomorrow", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActio.nStyle.cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: nil)) // show the alert
self.present(alert, animated: true, completion: nil)
}
}
Handling Button Taps
The handler
was nil
in the above examples. You can replace nil
with a closure to do something when the user taps a button. For example:
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertAction.Style.destructive, handler: { action in // do something like...
self.launchMissile()}))
Notes
- Multiple buttons do not necessarily need to use different
UIAlertAction.Style
types. They could all be.default
. - For more than three buttons consider using an Action Sheet. The setup is very similar. Here is an example.