UIAlertController Tutorial

UIAlertController Tutorial

UIAlertController is a subclass of UIViewController. It is an object that displays an interactive alert message. It can have actions and textFields. UIAlertController is very useful because you don’t need to code this simple alerts again and again (It is a pre-styled controller), and because it is very intuitive to IOS users.

1.UIAlertController Styles:

UIAlertController has 2 styles – actionSheet (left), alert (right). It is a values of preferredStyle property of UIAlertController.

2a. How to create UIAlertController?

In the code below we have 3 actions (UIAlertAction). It is buttons – Default, Destructive, and Cancel. Each action has a title, style, and handler property. The handler is a closure where we can handle actions tap events. Action has 3 styles – cancel, destructive, default. We can ignore the handler (set it to nil) of action with style “cancel“, it will close the popup without our code.

3. How to add UITextField to UIAlertController?

4. Complex example. preferredAction property

You can see above a complex example of alert with field and actions. You can pay attention to a specific action with preferredAction property. You can simply set your action to preferredAction and it will have bold font like Default 2 action.


  1. UIAlertController has 2 style – actionSheet , alert
  2. UIAlertController must be open only in modally mode. You can’t push it in a navigation controller like default UIViewController.
  3. UIAlertAction (buttons) has 3 styles – cancel, destructive, default
  4. UIAlertController can have UITextFields. You can add as many fields as you want
  5. You can’t add UITextFields to alert in actionSheet style
  6. Only one UIAlertAction with cancel style can exist in the alert. You can’t add more that one cancel action (Yes is it useless, but a fact)