Making an Alert in iOS

Suragch
2 min readJan 3, 2019

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

--

--

Suragch
Suragch

Written by Suragch

Flutter and Dart developer. Twitter: @suragch1, Email: suragch@suragch.dev

No responses yet