UIAlertController

The introduction of iOS8 brought big changes in regards to how alert boxes and action sheets are displayed to the user. Previously, we used UIAlertView and UIActionSheet separately to accomplish our goals. Now, these two alert types have been combined and can be reached via UIAlertController.

Getting started

We start by simply creating an instance of UIAlertController with preferredStyle property set to .Alert (UIAlertControllerStyleAlert).  We then present the alert controller using presentViewController.

let alertController = UIAlertController(title: "Error", message: "No internet connection", preferredStyle: .Alert)
                    
self.presentViewController(alertController, animated: true, completion:nil)

After we have created our UIAlertController we need to add the button(s). This is done with UIAlertAction and includes a callback block of code. This means you won’t have to write a separate function or add an observer to handle the button press. Isn’t Swift great?

let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction) in
 print("You've pressed OK button");
 }
   
alertController.addAction(OKAction)

 

Basic alert (1 button)

uialertcontroller-1-button

let alertController = UIAlertController(title: "Error", message: "No internet connection", preferredStyle: .Alert)
                    
       let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction) in
             print("You've pressed OK button");
       }
                   
alertController.addAction(OKAction)                    
self.presentViewController(alertController, animated: true, completion:nil)

Basic alert (2 buttons)

uialertcontroller-2-button

let alertController = UIAlertController(title: "Error", message: "No internet connection\nTry again?", preferredStyle: .Alert)
                    
       let actionYes = UIAlertAction(title: "Yes", style: .Default) { (action:UIAlertAction) in
             print("You've pressed the Yes button");
       }

       let actionNo = UIAlertAction(title: "No", style: .Default) { (action:UIAlertAction) in
             print("You've pressed No button");
       }
                   
alertController.addAction(actionYes)  
alertController.addAction(actionNo)                                      
self.presentViewController(alertController, animated: true, completion:nil)

UIAlertController with text input

uialertcontroller-text
UIAlertController makes it easy to add text boxes and read the values once a button is pressed.

We create an instance of UIAlertController like we normally would, adding a few important things: addTextFieldWithConfigurationHandler and code to read the value from the UITextField.

The method addTextFieldWithConfigurationHandler on UIAlertController is used to add textfields to the alert box. In this example, we set the attributes (placeholder & secure text) of the textfields inside this block of text.

You will also need to add a few lines of code to read the user’s text inputs. In this example, it’s being done in the “Login” button. UIAlertController has a textFields property. To access it, simply access the index value of the textbox. We added the “E-mail” textfield first, so that will be index 0. The password textfield is at index 1.

        let alertController = UIAlertController(title: "Login", message: "Please enter your credentials.", preferredStyle: .Alert)
        
        let actionCancel = UIAlertAction(title: "Cancel", style: .Cancel) { (action:UIAlertAction) in
            //This is called when the user presses the cancel button.
            print("You've pressed the cancel button");
        }
        
        let actionLogin = UIAlertAction(title: "Login", style: .Default) { (action:UIAlertAction) in
            //This is called when the user presses the login button.
            let textUser = alertController.textFields![0] as UITextField;
            let textPW = alertController.textFields![1] as UITextField

            print("The user entered:%@ & %@",textUser.text!,textPW.text!);
        }
        
        alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
            //Configure the attributes of the first text box.
            textField.placeholder = "E-mail"     
        }

        alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
            //Configure the attributes of the second text box.
            textField.placeholder = "Password"
            textField.secureTextEntry = true
        }
       
        //Add the buttons
        alertController.addAction(actionCancel)
        alertController.addAction(actionLogin)

        //Present the alert controller
        self.presentViewController(alertController, animated: true, completion:nil)
  

UIAlertController with action sheet

uialertcontroller-actionsheet

Since UIAlertController covers both alerts and action sheets, we use a similar initialization, simply changing the preferredStyle property to specifyUIAlertControllerStyle.ActionSheet instead of UIAlertControllerStyle.Alert. In the following example, we use the short dot syntax on the preferredStyle property, instead of writing out the entire UIAlertControllerStyle.ActionSheet text, we can simply type .ActionSheet. You will notice that we also make use of this shortened dot syntax with the UIAlertAction button styles.

//Create the alert controller
        let actionSheetController: UIAlertController = UIAlertController(title: "Choose action", message: "Would you like to learn more?", preferredStyle: .ActionSheet)
        
        //Create and add the "Cancel" action
        let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
            //Just dismiss the action sheet
        }
        actionSheetController.addAction(cancelAction)

        //Create and add "Yes" action
        let yesAction: UIAlertAction = UIAlertAction(title: "Yes", style: .Default) { action -> Void in
          
              //The user just pressed the Yes button.
        }
        
        actionSheetController.addAction(yesAction)
        
        //Present the AlertController
        self.presentViewController(actionSheetController, animated: true, completion: nil)

 

UIAlertController Button Styles

When using UIAlertController, you will want to make it very clear to your users what each button does. UIAlertActionStyle has three different button styles: Default, Cancel and Destructive. These styles apply to both alerts and action sheets. Choose the correct button for your specific use case.

enum UIAlertActionStyle : Int {
    case Default
    case Cancel
    case Destructive
}