Want to offer native, in-app customer service to your users? Get going quickly with Zendesk’s Mobile SDKs. Free with Zendesk.


#44: UIAlertController ⚠️


Alert Views and Action Sheets are some of the oldest parts of UIKit. In iOS 8, Apple overhauled how you create and display them using UIAlertController. Let's take a look at how it can improve the adaptability of your UI as well as the readability of your code:

@IBAction func launchButtonTapped(launchButton: UIButton) {
  let controller: UIAlertController = UIAlertController(
    title: "Where To?",
    message: "Where would you like to go?",
    preferredStyle: .ActionSheet

  controller.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))

  controller.addAction(UIAlertAction(title: "Home", style: .Default) { action in

  controller.addAction(UIAlertAction(title: "Pluto", style: .Default) { action in

  controller.popoverPresentationController?.sourceView = launchButton

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

First we create the controller, and set the style to .ActionSheet. We could have used .Alert instead, and our actions would be presented as an Alert View.

Then we add actions, each with a block callback that will fire when the action is selected. A nil handler will have no action.

Then we set .sourceView to the button that originated the action so our action sheet's arrow will ‘point' to the right spot on iPad.

And finally we present our controller just like any other view controller.