Cesare Cesare - 2 months ago 14x
iOS Question

Create an UIAlertAction in Swift

I would like to create the following



@IBAction func buttonUpgrade(sender: AnyObject) {

let alertController = UIAlertController(title: "Title",
message: "Message",
preferredStyle: UIAlertControllerStyle.Alert)

let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...


I'm aware that an
is initialized with a
, and whether it prefers to be displayed as an alert or action sheet.

When the button is pressed I would like to display the alert, but
doesn't work. Why doesn't my code work?


The main issue here is that UIAlertController (unlike UIAlertView) is a subclass of UIViewControlller, meaning it needs to be presented as such (and not via the show() method). Other than that, if you want to change to color of the cancel button to red, you have to set the cancel action's alert style to .Destructive.

This only works if you want the button to be red. If you want to change the colors of the buttons in the alert controller to arbitrary colors, this can only be done by setting the tintColor property on the alert controller's view property, which will change the tint color of all of its buttons (except those that are destructive). It should be noted that with the design paradigms that Apple has put in place, it isn't necessary to change the cancel button's color due to the implications of its having bolded text.

If you do still want the text to be red though, it can be done like this:

let alertController = UIAlertController(
    title: "Title",
    message: "Message",
    preferredStyle: UIAlertControllerStyle.Alert

let cancelAction = UIAlertAction(
    title: "Cancel",
    style: UIAlertActionStyle.Destructive) { (action) in
    // ...

let confirmAction = UIAlertAction(
    title: "OK", style: UIAlertActionStyle.Default) { (action) in
    // ...


presentViewController(alertController, animated: true, completion: nil)

Which produces the results you're after:

enter image description here