Using UIAlertController instead of good-old UIAlertView

Updated for iOS 9.3 in June 2016.

UIAlertView is surely familiar to every iOS developer, even newbie. However, in iOS 8 it has been deprecated and replaced with a mysterious UIAlertController.


At first, UIAlertController may seem more complicated than UIAlertView – for example it is now impossible to show an alert with only one line. Nevertheless, the new API provides much more advantages and makes the overall usage of alerts more elegant and easy. Let’s take a look at some simple examples.

A simple alert using UIAlertController

UIAlertController can be initialised with a title and a message. As UIAlertController can be also used to show an action sheet, you must provide a type for the controller. There’re only two options UIAlertControllerStyleAlert for alerts and UIAlertControllerStyleActionSheet for actionsheets.

In order to add a button, a special class named UIAlertAction should be used. The interesting part is that UIAlertAction now provides an action handler, which gets called when the button gets tapped. In comparison to the old API, where the only way to receive callbacks is to implement UIAlertViewDelegate protocol and to somehow determine, which alert it is (using tags or whatever tricks), it is definitely more convenient.

Finally, in order to show the alert, the controller should be presented modally like any other ordinary controller. Again, such a decision provides much more flexibility.

Sample code to show an easy alert like this:

Screen Shot 2014-10-11 at 20.28.11



Alert with more than 2 buttons

The new API provides an easy way to show much more than 2 buttons in an alert. It can be done by adding as much UIAlertActions, as you wish.

For example, let’s show 4 buttons:

Screen Shot 2014-10-11 at 20.36.54


And the code is as simple as that:



However, the device screen is limited in height, so don’t get too excited with buttons 🙂

Screen Shot 2014-10-11 at 20.41.15

Also note, adding more than one cancel action will raise an exception:



Adding textfields

Adding a textfield is also pretty easy and can be done using addTextFieldWithConfigurationHandler method. The method provides the added textfield within the block, thus making the created textfield fully customisable.

For example, you can set a placeholder, change a text colour etc. Retrieving the textfield text is also pretty easy, because UIAlertController provides array of all added textFields.



Screen Shot 2014-10-11 at 20.48.11

To conclude, getting used to the new API takes minimum amount of time, but it provides flexibility that iOS developers waited since iOS 4 or 5 🙂

Complete code

You can find the complete code here (tested with Xcode 7.3.1, iOS 9.3):

  1. Aalok
  2. Chetan Kumar

Leave a Reply

Your email address will not be published. Required fields are marked *