21

Couldn't find a clear and informative explanation for this.

Nikita Kurtin
  • 5,889
  • 4
  • 44
  • 48
  • 6
    The Stack Overflow format requires a question. If you want to answer your own question, you can, but you must first ask a question. Reformat your post in the form of the question you were trying to find an answer to, and then move your above post to the answer. – vacawama May 16 '15 at 14:01
  • You can use a `UIAlertController` for both an alert and an action sheet. I find examples the easiest way to understand how things work. Here is an [alert example](https://stackoverflow.com/a/33340757/3681880) and here is an [action sheet example](https://stackoverflow.com/a/32991999/3681880). – Suragch Jun 04 '17 at 14:24

3 Answers3

64

After searching a while on a subject I didn't find a clear explanation , even in it's class reference UIAlertController Reference

It is ok, but not clear enough for me.

So after collecting some peaces I decided to make my own explanation (Hope it helps)

So here it goes:

  1. UIAlertView is deprecated as pointed out : UIAlertView in Swift
  2. UIAlertController should be used in iOS8+ so to create one first we need to instantiate it, the Constructor(init) gets 3 parameters:

2.1 title:String -> big-bold text to display on the top of alert's dialog box

2.2 message:String -> smaller text (pretty much explains it's self)

2.3 prefferedStyle:UIAlertControllerStyle -> define the dialog box style, in most cases: UIAlertControllerStyle.Alert

  1. Now to actually show it to the user, we can use showViewController or presentViewController and pass our alert as parameter

  2. To add some interaction with a user we can use:

4.1 UIAlertController.addAction to create buttons

4.2 UIAlertController.addTextField to create text fields

Edit note: code examples below, updated for swift 3 syntax

Example 1: Simple Dialog

@IBAction func alert1(sender: UIButton) {
     //simple alert dialog
    let alert=UIAlertController(title: "Alert 1", message: "One has won", preferredStyle: UIAlertControllerStyle.alert);
    //show it
    show(alert, sender: self);
}

Example 2: Dialog with one input textField & two buttons

@IBAction func alert2(sender: UIButton) {
    //Dialog with one input textField & two buttons
    let alert=UIAlertController(title: "Alert 2", message: "Two will win too", preferredStyle: UIAlertControllerStyle.alert);
    //default input textField (no configuration...)
    alert.addTextField(configurationHandler: nil);
    //no event handler (just close dialog box)
    alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.cancel, handler: nil));
    //event handler with closure
    alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: {(action:UIAlertAction) in
        let fields = alert.textFields!;
        print("Yes we can: "+fields[0].text!);
    }));
    present(alert, animated: true, completion: nil);
}

Example 3: One customized input textField & one button

@IBAction func alert3(sender: UIButton) {
   // one input & one button
   let alert=UIAlertController(title: "Alert 3", message: "Three will set me free", preferredStyle: UIAlertControllerStyle.alert);

    //configured input textField
    var field:UITextField?;// operator ? because it's been initialized later
    alert.addTextField(configurationHandler:{(input:UITextField)in
        input.placeholder="I am displayed, when there is no value ;-)";
        input.clearButtonMode=UITextFieldViewMode.whileEditing;
        field=input;//assign to outside variable(for later reference)
    });
    //alert3 yesHandler -> defined in the same scope with alert, and passed as event handler later
    func yesHandler(actionTarget: UIAlertAction){
        print("YES -> !!");
        //print text from 'field' which refer to relevant input now
        print(field!.text!);//operator ! because it's Optional here
    }
    //event handler with predefined function
    alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: yesHandler));

    present(alert, animated: true, completion: nil);
 }

Hope It helps, and good luck ;-)

Community
  • 1
  • 1
Nikita Kurtin
  • 5,889
  • 4
  • 44
  • 48
  • 2
    I am glad that you have shared, what you learned!! thank you so much for step by step explanation.. like minded ;) – swiftBoy Mar 21 '16 at 11:11
  • I am running on Xcode 7.3.1 and testing on iOS9. When using showViewController(alert, sender: self) from first example with UINavigationController (without it's ok) I was getting weird behaviour. It adds the alert view to the navigation bar. Using self.presentViewController(alert, animated: true, completion: nil) works fine. – pls Jul 19 '16 at 08:08
  • Yes I've noticed that too and it seems to happen, because of the differences between those methods: [showViewController](https://developer.apple.com/reference/uikit/uinavigationcontroller/1621872-showviewcontroller?language=objc) _pushes vc onto the navigation stack in a similar way as the pushViewController_, but [presentViewController](https://developer.apple.com/reference/uikit/uiviewcontroller/1621380-presentviewcontroller?language=objc) _displays view controller modally over the current view controller_ – Nikita Kurtin Jul 19 '16 at 09:44
  • 1
    Thanks for the good info, but are you sure you need the semi-colons in Swift? – Ethan Parker Dec 01 '16 at 21:05
  • @EthanParker `Unlike many other languages, Swift does not require you to write a semicolon (;) after each statement in your code, although you can do so if you wish.` I personally prefer _cross languages_ code style, therefore you see it in my examples. – Nikita Kurtin Dec 02 '16 at 09:49
11

An instance of the UIAlertController can be presented modally on screen just as any other UIViewController using the presentViewController:animated:completion: method. What makes the UIAlertController instance differentiate between working as an ActionSheet or as an AlertView is the style parameter you pass when creating it.

No more delegation

If you have used a UIActionSheet or UIAlertView, you know that the way to get a callback from it is for a class (in most cases the ViewController) to implement the UIActionSheetDelegate or UIAlertViewDelegate protocol. There are some open source projects that replaced this delegation pattern with block based callbacks, but the official APIs were never updated. UIAlertController does not use delegation. Instead, it has a collection of UIAlertAction items, that use closures (or blocks if you are using Objective-C) to handle user input.

For Action Sheet

@IBAction func showActionSheet(sender: AnyObject) {
  //Create the AlertController
  let actionSheetController: UIAlertController = UIAlertController(title: "Action Sheet", message: "Swiftly Now! Choose an option!", 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 first option action
  let takePictureAction: UIAlertAction = UIAlertAction(title: "Take Picture", style: .Default) { action -> Void in
    //Code for launching the camera goes here
    }
  actionSheetController.addAction(takePictureAction)
  //Create and add a second option action
  let choosePictureAction: UIAlertAction = UIAlertAction(title: "Choose From Camera Roll", style: .Default) { action -> Void in
    //Code for picking from camera roll goes here
    }
  actionSheetController.addAction(choosePictureAction)

  //Present the AlertController
  self.presentViewController(actionSheetController, animated: true, completion: nil)
}

For AlertView with Text Field

@IBAction func showAlert(sender: AnyObject) {
  //Create the AlertController
  let actionSheetController: UIAlertController = UIAlertController(title: "Alert", message: "Swiftly Now! Choose an option!", preferredStyle: .Alert)

  //Create and add the Cancel action
  let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
    //Do some stuff
    }
  actionSheetController.addAction(cancelAction)
    //Create and an option action
  let nextAction: UIAlertAction = UIAlertAction(title: "Next", style: .Default) { action -> Void in
    //Do some other stuff
    }
  actionSheetController.addAction(nextAction)
  //Add a text field
  actionSheetController.addTextFieldWithConfigurationHandler { textField -> Void in
       //TextField configuration
     textField.textColor = UIColor.blueColor()
   }

   //Present the AlertController
   self.presentViewController(actionSheetController, animated: true, completion: nil)
}
Omer Waqas Khan
  • 2,423
  • 4
  • 33
  • 62
  • Thank you for contribution, even I've already answered it half a year ago. Still its very nice answer so I gladly voted up ;-) BTW, you can also show the alert with showViewController method - less flexible, but make sense when completion no needed – Nikita Kurtin Oct 28 '15 at 20:18
1

Some of the syntax has changed since the original responses. Here is some sample code that alerts the user if they are not signed in to iCloud.

CKContainer.default().accountStatus { (accountStatus, error) in
        switch accountStatus {
        case .available:
            print("iCloud Available")
        case .noAccount:
            print("No iCloud account")
            //simple alert dialog
            let alert=UIAlertController(title: "Sign in to iCloud", message: "This application requires iClound. Sign in to your iCloud account to write records. On the Home screen, launch Settings, tap iCloud, and enter your Apple ID. Turn iCloud Drive on. If you don't have an iCloud account, tap Create a new Apple ID", preferredStyle: UIAlertControllerStyle.alert);
            //no event handler (just close dialog box)
            alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil));
            //show it
            self.present(alert, animated: true, completion: nil)
        case .restricted:
            print("iCloud restricted")
        case .couldNotDetermine:
            print("Unable to determine iCloud status")
        }
    }
Pang
  • 9,564
  • 146
  • 81
  • 122
CliffAnd
  • 11
  • 2