Member-only story

Making an Alert in iOS

Suragch

--

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

--

--

No responses yet

Write a response