An object that displays an alert message to the user.


Use this class instead of UIActionSheet and UIAlertView to display alerts. After configuring the alert controller with the actions and style you want, present it using the present(_:animated:completion:) method.

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

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert"
                               message:@"This is an alert."
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
   handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];

When configuring an alert with the 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.


The UIAlertController class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.


Creating an Alert Controller

init(title: String?, message: String?, preferredStyle: UIAlertControllerStyle)

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: UIAlertControllerStyle

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 UIAlertControllerStyle

Constants indicating the type of alert to display.

See Also


class UIAlertAction

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