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:
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:
And the code is as simple as that:
However, the device screen is limited in height, so don’t get too excited with buttons 🙂
Also note, adding more than one cancel action will raise an exception:
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.
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 🙂
You can find the complete code here (tested with Xcode 7.3.1, iOS 9.3):