Use of uialertcontroller

Time:2021-3-9

When your application needs to present important information to users or prompt users for important choices, you can use alert view and action sheet. The left part of the figure below is the warning box, and the right part is the operation table.
Use of uialertcontroller

Since IOS 8, Apple has usedUIViewControllerOfUIAlertControllerInstead ofUIAlertViewandUIAlertSheet

Although UIalert controller has two forms: warning box and operation table, its creation steps are the same. As follows:

  1. establishUIAlertControllerTo specify the alert controller style.
  2. Add a button to the alarm controller.
  3. displayUIAlertController

1. Create demo

Let’s learn it through demo.

Open Xcode, click File > New > Project , select IOS > Application > single view application template, and clickNext; inProduct NameFill in theAlertController, clickNext; select the file and clickCreateCreate a project.

Open the project you just createdstoryboard, instoryboardThe following controls are added from top to bottom in theUIAlertControllerStyleAlertOfUILabel, namedShow AlertOfUIButton, namedLogin AlertOfUIButton, the content isUIAlertControllerStyleActionSheetOfUILabel, namedAction SheetOfUIButton. As shown in the figure below:

Use of uialertcontroller

holdUIButtonDrag toViewController.mInterface part of, type isIBAction. The code is as follows:

#import "ViewController.h"

@interface ViewController ()

- (IBAction)showAlertView:(UIButton *)sender;
- (IBAction)showLoginAlertView:(UIButton *)sender;
- (IBAction)showActionSheet:(UIButton *)sender;

@end

2. Simple dialog style

2.1 create alarm controller

establishUIAlertControllerIt’s very simple. You don’t need to set a proxy or specify a button.

Let’s start withshowAlertView: Method, createUIAlertController

- (IBAction)showAlertView:(UIButton *)sender
{
    //1. Create uialertcontroller
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert Title"
                                                                             message:@"The message is ..."
                                                                      preferredStyle:UIAlertControllerStyleAlert];
}

therepreferredStyle: The parameters areUIAlertControllerStyleAlertandUIAlertControllerStyleActionSheetTwo, here we’re going to createAlert ViewSo use the first one.

2.2 add button

useactionWithTitle: style: handler: Method creationUIAlertActionObject, and then add the object to the alert controller.

UIAlertActionThe object consists of a title, a style, and a code block that runs when the user clicks the button.UIAlertActionStyleThere are three styles, style oneUIAlertActionStyleCancel, which is used to cancel the operation without any modificationcancelButton; style 2UIAlertActionStyleDefault, the default style of the button; the third isUIAlertActionStyleDestructive, which is used to change or delete data. The title of the button in this style will be displayed in red automatically.

stayshowAlertView: MethodCancelButtons andOKButton.

- (IBAction)showAlertView:(UIButton *)sender
{
    ...
    //2. Create and add buttons
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"OK Action");
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Cancel Action");
    }];

    [alertController addAction:okAction];           // A
    [alertController addAction:cancelAction];       // B
}

2.3 displayUIAlertController

displayUIAlertController

- (IBAction)showAlertView:(UIButton *)sender
{
    ...
    //3. Present UIalert contoller
    [self presentViewController:alertController animated:YES completion:nil];
}

clickShow AlertButton, the view controller displays as follows:

Use of uialertcontroller

Change the topaddAction: Method order, run app, you will find that the order of the buttons in alert view does not change. When the alert view style hasCancelButton,CancelButtons always appear on the left, regardless of the order in which they are added.

stayshowAlertView: MethodUIAlertActionStyleDestructiveStylizedResetButton.

- (IBAction)showAlertView:(UIButton *)sender
{
    ...
    UIAlertAction *resetAction = [UIAlertAction actionWithTitle:@"Reset" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Reset Action");
    }];
    [alertController addAction:resetAction];        // C
    [alertController addAction:okAction];           // A
    [alertController addAction:cancelAction];       // B
    ...
}

Run the demo as follows:

Use of uialertcontroller

When there are one or two buttons in alert view, the buttons will be arranged horizontally; when there are more than two buttons, they will be displayed vertically like action sheet. Put it on the topaddAction: The method order is changed to B, a, C. run the app, and the view controller is displayed as follows:

Use of uialertcontroller

You can see that as long as there’s something on itUIAlertActionStyleCancelThis button is always at the bottom, and the order of other buttons is determined by the order of adding. If includedUIAlertActionStyleDestructiveStyle buttons are usually added first so that they can be displayed in the first position. Each alarm controller can only contain one alarm controllerCancelButton, if you add two or more, will be thrown at run timeNSInternalInconsistencyExceptionIt’s abnormal.

3. Login text box

UIAlerControllerAnother use of is that we can add any number of alarms to the alarm controllerUITextFieldAs part of the alert controller content view. For example, the common landing box.

Use of uialertcontroller

To create a login box like the one above, we need to add two text boxes to the alert controller. Add appropriate placeholders to each text box to prompt you to enter the type of text information, and enable secure text for the text box that needs to enter a password to ensure password security. UpdatedshowLoginAlertView: The code is as follows:

- (IBAction)showLoginAlertView:(UIButton *)sender
{
    //1. Create uialertcontroller
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Login"
                                                                             message:@"Enter Your Account Info Below"
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    
    //2.1 add text box
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"username";
    }];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"password";
        textField.secureTextEntry = YES;
    }];
}

Continue inshowLoginAlertView: MethodCancelButtons andLoginButton, clickLoginButton to get the account and password in the text box and output to the console.

- (IBAction)showLoginAlertView:(UIButton *)sender
{
    ...
    //2.2 create cancel login button
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Cancel Action");
    }];
    UIAlertAction *loginAction = [UIAlertAction actionWithTitle:@"Login" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *userName = alertController.textFields.firstObject;
        UITextField *password = alertController.textFields.lastObject;
        
        //Output user name and password to console
        NSLog(@"username is %@, password is %@",userName.text,password.text);
    }];
}

In the code above,UIAlertControllerwithintextFieldsThe order of elements in the array is consistent with the order of adding.

Finally, add a button to display the alarm controller.

- (IBAction)showLoginAlertView:(UIButton *)sender
{
    ...
    //2.3 add button
    [alertController addAction:cancelAction];
    [alertController addAction:loginAction];
    
    //3. Display alarm controller
    [self presentViewController:alertController animated:YES completion:nil];
}

Now run the app and type in the first text boxpro648, enter in the second text boxx, clickLoginButton, the console output is as follows:

username is pro648, password is x

In practical application, we usually limit the length of user name and password, when the length is insufficient, it should be disabledLoginButton. We can do this by adding aUIControllEventEditingChangedResponse events. Remember to disable the button before adding it. The updated code is as follows:

- (IBAction)showLoginAlertView:(UIButton *)sender
{
    ...
    //2.1 add text box
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"username";
        
        [textField  addTarget:self action :@selector (alertUserAccountInfoDidChange:) forCont rolEvents:UIControlEventEditingChanged ]; // add response events
    }];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"password";
        textField.secureTextEntry = YES;
        
        [textField  addTarget:self action :@selector (alertUserAccountInfoDidChange:) forCont rolEvents:UIControlEventEditingChanged ]; // add response events
    }];
    
    ...
    //2.3 add button
    loginAction.enabled  =No; // disable the login button
    [alertController addAction:cancelAction];
    [alertController addAction:loginAction];
    ...
}

- (void)alertUserAccountInfoDidChange:(UITextField *)sender
{
    UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
    
    if (alertController)
    {
        NSString *userName = alertController.textFields.firstObject.text;
        NSString *password = alertController.textFields.lastObject.text;
        UIAlertAction *loginAction = alertController.actions.lastObject;
        
        if (userName.length > 3 && password.length > 6)
            //When the user name is more than 3 digits and the password is more than 6 digits, the login button is enabled.
            loginAction.enabled = YES;
        else
            //If the user name is less than or equal to 3 digits and the password is less than or equal to 6 digits, the login button is disabled.
            loginAction.enabled = NO;
    }
}

UIAlertControllerIntextFieldsandactionsAll are array types. The first object added is index0. After that, add 1 in the order of adding index, although we mentioned aboveCancelButtons are generally displayed on the left (horizontal) or bottom (vertical), but it does not mean that their position in the array is the first or last. Their index is determined by the order of addition. You can useusernameString length to disableLoginButton to test.

Now only when the user name is more than three digits and the password is more than six digits,LoginButton to click.

Use of uialertcontrollerUse of uialertcontroller

4. Action sheet

Operation table is generally used to provide users with a set of optional operation options, such as delete, restore, etc. On the iPhone, the operation table slides out from the bottom; on the iPad, the operation table appears as a pop-up box.

The method of creating an action table is similar to that of a warning box, except thatpreferredStyle: Parameter selection. stayshowActionSheet: Method.

- (IBAction)showActionSheet:(UIButton *)sender
{
    //1. Create uialertcontroller
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Action Sheet"
                                                                             message:@"Deleted data can't be restored"
                                                                      preferredStyle:UIAlertControllerStyleActionSheet];
}

Next, create and add buttons, and finally present the alert controller.

- (IBAction)showActionSheet:(UIButton *)sender
{
    ...
    //2.1 create button
    UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"Delete" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Delete Action");
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Cancel Action");
    }];
    
    //2.2 add button
    [alertController addAction:deleteAction];
    [alertController addAction:cancelAction];
    
    //3. Display alarm controller
    [self presentViewController:alertController animated:YES completion:nil];
}

Run the app, and the operation table is as follows:

Use of uialertcontroller

IfAction SheetThere is a cancel button in. The Cancel button will be displayed at the bottom every time. Other buttons will be displayed in the order of adding. You cannot add a text box inside an action sheet. If you add a text box, the following exception alert will be thrown at runtime:

* Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘Text fields can only be added to an alert controller of style UIAlertControllerStyleAlert’

As mentioned above, in the iPad, the action sheet is presented as a pop-up box. Pop ups always need an anchor, which can be a source view or a button. In this demo, we use the button to trigger the pop-up box, so we will use the button as the anchor here.showActionSheet: The method is updated as follows:

- (IBAction)showActionSheet:(UIButton *)sender
{
    ...
    UIPopoverPresentationController *popover = alertController.popoverPresentationController;
    if (popover)
    {
        popover.sourceView = sender;
        popover.sourceRect = sender.bounds;
        popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
    }
    
    //3. Display alarm controller
    [self presentViewController:alertController animated:YES completion:nil];
}

If the above method is not added to the iPad, the following crash prompt will appear at runtime:

* Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘Your application has presented a UIAlertController (<UIAlertController: 0x7f88c85221f0>) of style UIAlertControllerStyleActionSheet. The modalPresentationStyle of a UIAlertController with this style is UIModalPresentationPopover. You must provide location information for this popover through the alert controller’s popoverPresentationController. You must provide either a sourceView and sourceRect or a barButtonItem. If this information is not known when you present the alert controller, you may provide it in the UIPopoverPresentationControllerDelegate method -prepareForPopoverPresentation.’

Now, the action sheet is displayed as a pop-up box, anchored by the button that triggered it.

Use of uialertcontroller

When the action sheet is displayed as a pop-up box,UIKitThe display will be cancelledCancelButton. At this point, click any area outside the Popper and clickCancelButton effect is consistent, and the Cancel button completion handler will be called.

5. Exit the alarm controller

The alarm controller will automatically disappear after the user clicks the button, but when the app enters the background, the warning box and selection table will not automatically exit. At this point, we need to exit the alarm controller through code.

Register in the notification center and exit the alarm controller when receiving the notification that the app enters the background. UpdatedviewDidLoadAs follows:

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //Hide the alarm controller after the app enters the background
    [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        [self.presentedViewController dismissViewControllerAnimated:YES completion:nil];
    }];
}

- (void)dealloc
{
    //Remove observer
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}

Finally, remember to remove the observer, otherwise it will cause a crash.

summary

The following summarizes the similarities and differences between alert view and action sheet.

Alert view:

  • Generally, it is displayed in the center of the current view controller, and the warning controller cannot be hidden by clicking the area outside the warning box.
  • You can add any number of text boxes.
  • There are one or two buttons when arranged horizontally, if anyCancelButton, thenCancelThe buttons are displayed on the left; when there are more than two buttons, they are arranged in vertical columns, if anyCancelButton, thenCancelThe button is displayed at the bottom. The other buttons are arranged in the order of addition.

Action sheet:

  • In the iPhone, it will slide from bottom to top and display at the bottom of the current controller. Click the area outside the action sheet to hide itUIAlertController
  • In iPad, the warning controller is displayed in Popover mode with source view as anchor point. Click the area outside the selection table to hide the warning controller.
  • Cannot add text box.
  • The buttons are arranged vertically in the iPhone,CancelThe buttons are displayed at the bottom by default; on the iPad,CancelThe button is not displayed by default.

UIAlertControllerClass can only be used as is and does not support subclassing. The view hierarchy of this class is private and cannot be modified. Finally, it should be noted that when the warning box and operation table display information to the user, the current process of the application will be interrupted. Please use it only when necessary, and do not abuse it.

Demo Name: alertcontroller
Source code address: https://github.com/pro648/Bas…

reference material:

  1. UIAlertController Changes in iOS 8
  2. UIAlertController

More corrections are welcome https://github.com/pro648/tip…

Address: https://github.com/pro648/tip…