Adding multiple actions to UIAlertController

When making an iOS app you will find that there are many situations in which you want to show an alert or an action sheet to the user to have him confirm or choose between a set of actions. The current API can make this process a little bit too verbose:

let alertController = UIAlertController(  
    title: "Are you sure about this?",
    message: "Well, are you?",
    preferredStyle: .Alert
)

let confirmAction = UIAlertAction(title: "Do it", style: .Default, handler: doItHandler)  
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)

alertController.addAction(confirmAction)  
alertController.addAction(cancelAction)  
alertController.preferredAction = cancelAction

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

So, I made a simple extension to make this process look a little more clean:

alertController.addActions([  
    UIAlertAction(title: "Do it", style: .Default, handler: doItHandler),
    UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
], preferred: "Cancel")

The preferred flag should be set to the title of the preferred action, but can be left out if unwanted. Here is the full extension:

import UIKit

extension UIAlertController {  
  func addActions(actions: [UIAlertAction], preferred: String? = nil) {

    for action in actions {
      self.addAction(action)

      if let preferred = preferred where preferred == action.title {
        self.preferredAction = action
      }
    }
  }
}

Note: This implementation is Localization insensitive. Simply replace preferred with a preferredIndex into the array for Localization support.

Frederik Nakstad

Read more posts by this author.

Tokyo, Japan