An object that displays an alert message to the user.


class UIAlertController : UIViewController


Use this 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.

In addition to displaying a message to a user, you can associate actions with your alert controller to give the user a way to respond. For each action you add using the addAction(_:) method, the alert controller configures a button with the action details. When the user taps that action, the alert controller executes the block you provided when creating the action object. Listing 1 shows how to configure an alert with a single action.

Listing 1

Configuring and presenting an alert

let alert = UIAlertController(title: "My Alert", message: "This is an alert.", preferredStyle: .alert) 
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .default, handler: { _ in 
NSLog("The \"OK\" alert occured.")
self.present(alert, animated: true, completion: nil)

When configuring an alert with the UIAlertController.Style.alert style, you can also add text fields to the alert interface. The alert controller lets you provide a block for configuring your text fields prior to display. The alert controller maintains a reference to each text field so that you can access its value later.


Creating an Alert Controller

init(title: String?, message: String?, preferredStyle: UIAlertController.Style)

Creates and returns a view controller for displaying an alert to the user.

Configuring the Alert

var title: String?

The title of the alert.

var message: String?

Descriptive text that provides more details about the reason for the alert.

var preferredStyle: UIAlertController.Style

The style of the alert controller.

Configuring the User Actions

func addAction(UIAlertAction)

Attaches an action object to the alert or action sheet.

var actions: [UIAlertAction]

The actions that the user can take in response to the alert or action sheet.

var preferredAction: UIAlertAction?

The preferred action for the user to take from an alert.

Configuring Text Fields

var textFields: [UITextField]?

The array of text fields displayed by the alert.


enum UIAlertController.Style

Constants indicating the type of alert to display.

See Also


Getting the User's Attention with Alerts and Action Sheets

Present important information to the user or prompt the user about an important choice.

class UIAlertAction

An action that can be taken when the user taps a button in an alert.