Class

UIAlert​Controller

A UIAlert​Controller object displays an alert message to the user. This class replaces the UIAction​Sheet and UIAlert​View classes for displaying alerts. After configuring the alert controller with the actions and style you want, present it using the present(_:​animated:​completion:​) method.

Overview

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 add​Action(_:​) 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."
                               preferredStyle:UIAlertControllerStyleAlert];
 
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.

Subclassing

The UIAlert​Controller 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.

Symbols

Creating an Alert Controller

init(title:​ String?, message:​ String?, preferred​Style:​ UIAlert​Controller​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.

Configuring the User Actions

func add​Action(UIAlert​Action)

Attaches an action object to the alert or action sheet.

var actions:​ [UIAlert​Action]

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

var preferred​Action:​ UIAlert​Action?

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

Configuring Text Fields

Constants

UIAlert​Controller​Style

Constants indicating the type of alert to display.