Stuart Breckenridge

UIAlertController Preferred Action

In a scenario where your UIAlertController alerts only have .Default actions, how do you add emphasis to what should be considered the preferred action of the user? Prior to iOS 9, this wasn’t possible without using a .Cancel action type, or creating your UIAlertController-like class from scratch. Enter preferredAction.

Let’s look at an example:

let alert = UIAlertController(title: "Send Error", message: "Your email failed to send.", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Try Again", style: .Default, handler: nil))
alert.addAction(UIAlertAction(title: "Remind Me Later", style: .Default, handler: nil))
alert.addAction(UIAlertAction(title: "Delete Draft", style: .Destructive, handler: nil))
presentViewController(alert, animated: true, completion: nil)

The above code will present a UIAlertController as follows:

UIAlertController Example 1

There is no obvious default action being highlighted to the user. To set a preferredAction, you just add this piece of code prior to presentViewController...:

alert.preferredAction = alert.actions[1] // Remind Me Later is at index 1 in the actions array.

Voila! Emphasis has been added to what should be considered as the preferred action.

UIAlertController Example 1