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.
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.
- UIAlertController has 2 style – actionSheet , alert
- UIAlertController must be open only in modally mode. You can’t push it in a navigation controller like default UIViewController.
- UIAlertAction (buttons) has 3 styles – cancel, destructive, default
- UIAlertController can have UITextFields. You can add as many fields as you want
- You can’t add UITextFields to alert in actionSheet style
- 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)