IOS -- what is between UIAlertView and UIAlertController and UIAlertAction?
One of the new features of iOS 8 is to make interfaces more adaptive and flexible, so many view controllers have undergone great changes in implementation methods. Brand newUIPresentationControllerIt plays an important role in implementing transition animation effects between view controllers and adaptive device size changes (for example, rotating). It effectively saves the workload of programmers ). Also, some oldUIKitControls have also undergone many changes, suchAlert Views,Action Sheets,PopoversAndSearch Bar Controllers. This article willAlert ViewsAndAction SheetsMake a general introduction to the changes that occur, using Objective-C
With the last release of iOS 5, the style of the dialog box view appeared in front of us, and it hasn't changed much until now. The following code snippet shows how to initialize and display a dialog box view with the "cancel" and "OK" buttons.
UIAlertView * alertview = [[UIAlertView alloc] initWithTitle: @ "title" message: @ "the default style of UIAlertView" delegate: self cancelButtonTitle: @ "cancel" otherButtonTitles: @ "OK", nil]; [alertview show];
Default style of UIAlertView
You must be able to create the same dialog box view as above.
Var alertView = UIAlertView () alertView. delegate = selfalertView. title = "title" alertView. message = "this is the default style of UIAlertView" alertView. addButtonWithTitle ("cancel") alertView. addButtonWithTitle ("good") alertView. show ()
You can also changeUIAlertViewOfalertViewStyleAttribute.
UIAlertView text dialog box
UIAlertView Password dialog box
UIAlertView logon dialog box
UIAlertViewDelegateThe callback Method for button actions in the response dialog box view. And when the content of the text box changes, callalertViewShouldEnableOtherButton:The button can be dynamically available or unavailable.
It should be noted that Apple does not currently advocate the use of iOS 8UIAlertViewInsteadUIAlertController. Next we will introduceUIAlertController.
In iOS 8,UIAlertControllerAndUIAlertViewAndUIActionSheetSame,UIAlertControllerThe functions and functions of the two products are replaced by a modular replacement method. Whether the dialog box (alert) or the action sheet is used depends on how you set the preferred style when creating the controller.
- A simple dialog box example
You can compare the code of the two different create dialog boxes to create a basicUIAlertControllerCode and CreationUIAlertViewThe code is very similar:
UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @ "title" message: @ "this is the default style of UIAlertController" preferredStyle: UIAlertControllerStyleAlert];
Same CreationUIAlertViewIn contrast, you do not need to specify a proxy or a button during initialization. However, pay special attention to the third parameter. Make sure that you select the dialog box style or the top menu style.
By creatingUIAlertActionYou can add the action button to the Controller.UIAlertActionIt consists of a title string, a style, and a code block that is run when the user selects the action. PassUIAlertActionStyleYou can select the following three action styles: regular (default), canceled (cancel), and warning (destruective ). In order to implement the originalUIAlertViewYou only need to create these two Action Buttons and add them to the Controller.
UIAlertAction * cancelAction = [UIAlertAction actionWithTitle: @ "cancel" style: incluhandler: nil]; UIAlertAction * okAction = [UIAlertAction actionWithTitle: @ "OK" style: incluhandler: nil]; [alertController addAction: cancelAction]; [alertController addAction: okAction];
Finally, we only need to display the View Controller of this dialog box:
[self presentViewController:alertController animated:YES completion:nil];
UIAlertController default Style
The order in which buttons are displayed depends on the order they are added to the Controller of the dialog box. Generally, according to the iOS User Interface Guide officially developed by Apple, you should put the cancel button on the left in the dialog box with two buttons. Note that the cancel button isUniqueIf you add the second cancel button, you will get the following runtime exception:
* Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘UIAlertController can only have one action with a style of UIAlertActionStyleCancel’
The exception information is concise and clear, so we will not go into details here.
What is the "alert" style? Let's not rush to answer this question. Let's take a look at the simple example of the "alert" style below the remark. In this example, we replace the "OK" button in the previous example with the "reset" button.
UIAlertAction * resetAction = [UIAlertAction actionWithTitle: @ "reset" style: UIAlertActionStyleDestructive handler: nil]; [alertController addAction: resetAction];
Alert Style
The new "reset" button turns red. According to Apple's official definition, the "alert" button is used for operations that may change or delete data. Therefore, a red icon is used to warn users.
UIAlertControllerGreat flexibility means you don't have to stick to built-in styles. In the past, we can only select the default view, text box view, password box view, login and password input box view. Now we can add any number to the dialog box.UITextFieldObject, and allUITextFieldFeatures. When you add a text box to the dialog box controller, you must specify a code block to configure the text box.
For example, to re-create the original login and password Style dialog box, we can add two text boxes to it and configure them with appropriate placeholders, finally, set the password input box to safe text input.
UIAlertController * alertController = [UIAlertController login: @ "text dialog box" message: @ "logon and Password dialog box example" preferredStyle: Login]; [alertController addTextFieldWithConfigurationHandler: ^ (UITextField * textField) {textField. placeholder = @ "login" ;}]; [alertController addTextFieldWithConfigurationHandler: ^ (UITextField * textField) {textField. placeholder = @ "password"; textField. secureTextEntry = YES;}];
When the "OK" button is pressed, let the program read the value in the text box.
UIAlertAction * okAction = [UIAlertAction actionWithTitle: @ "OK" style: UIAlertActionStyleDefault handler: ^ (UIAlertAction * action) {UITextField * login = alertController. textFields. firstObject; UITextField * password = alertController. textFields. lastObject;
NSLog (@ "account: % @", login. text );
NSLog (@ "password: % @", password. text );
}];
If we want to implementUIAlertViewDelegate method inalertViewShouldEnableOtherButton:Method may be complicated. Assume that the "OK" button can be activated only when the "login" text box contains at least three characters. UnfortunatelyUIAlertControllerThere is no corresponding delegate method, so we need to add an Observer to the "login" text box. The Observer mode defines one-to-many dependencies between objects. When the status of an object changes, all objects dependent on it are notified and automatically updated. You can add the following code snippets to construct a code block.
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){ ... [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField];}];
When the View Controller is released, we need to remove this Observer. We use the handler code block in each button action (there is anything else that might release the View Controller) add the appropriate code to implement it. For example, in the okAction button action:
UIAlertAction * okAction = [UIAlertAction actionWithTitle: @ "OK" style: UIAlertActionStyleDefault handler: ^ (UIAlertAction * action ){... [[nsicationcenter center defacenter center] removeObserver: self name: UITextFieldTextDidChangeNotification object: nil] ;}];
Before the dialog box is displayed, We need to freeze the "OK" button.
okAction.enabled = NO;
Next, in notification observer, we need to check the content of the "login" text box before activating the button status.
- (void)alertTextFieldDidChange:(NSNotification *)notification{ UIAlertController *alertController = (UIAlertController *)self.presentedViewController; if (alertController) { UITextField *login = alertController.textFields.firstObject; UIAlertAction *okAction = alertController.actions.lastObject; okAction.enabled = login.text.length > 2; }}
Example of the logon and Password dialog box for UIAlertController
Okay, now the "OK" button in the dialog box is frozen, unless you enter more than three characters in the "login" text box:
When you need to show users a series of options (select the killer of patients with phobias), the top menu can be used. Unlike the dialog box, the display format of the pull-up menu depends on the device size. On the iPhone (tightening width), the top menu is raised from the bottom of the screen. On the iPad (General width), pull the menu to display it in a pop-up box.
The method for creating a pull-on menu is similar to that for creating a dialog box. The only difference is their form.
UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @ "Save or delete data" message: @ "data deletion will not be recoverable" preferredStyle: UIAlertControllerStyleActionSheet];
The Add button action is the same as that in the dialog box.
UIAlertAction * cancelAction = [UIAlertAction actionWithTitle: @ "cancel" style: incluhandler: nil]; UIAlertAction * deleteAction = [UIAlertAction actionWithTitle: @ "delete" style: incluhandler: nil] UIAlertAction * archiveAction = [UIAlertAction actionWithTitle: @ "save" style: handler: nil]; [alertController addAction: cancelAction]; [alertController addAction: deleteAction]; [alertController addAction: archiveAction];
You cannot add a text box in the upper menu. If you forcibly Add a text box, you will be honored to get a runtime exception:
* Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘Text fields can only be added to an alert controller of style UIAlertControllerStyleAlert’
Similarly, we will not talk much about the simple exception description.
Next, we can show it on the iPhone or other devices with a tight width. As expected, the operation was successful.
[self presentViewController:alertController animated:YES completion:nil];
Pull-on menu effects on iPhone
If there is a "cancel" button in the top menu, it will always appear at the bottom of the menu, regardless of the order of addition (that is, so capricious ). Other buttons are displayed from top to bottom in the order of addition. The iOS User Interface Guide requires all the "warning" style buttons to be ranked first (well, I understand it well, right ?).
Don't be too excited. We have another serious problem, which is hidden. When we use an iPad or other devices of the regular width, an exception occurs:
Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘UIPopoverPresentationController (<_UIAlertControllerActionSheetRegularPresentationController: 0x7fc619588110>) should have a non-nil sourceView or barButtonItem set before the presentation occurs.’
As we said before, on a device of the regular width, the top menu isDialog Box. The pop-up box must have an anchor point that can be used as the source view or column button ). In this example, we use the regularUIButtonTo trigger the pull menu, so we use it as a stroke.
In iOS 8, we no longer need to carefully calculate the size of the pop-up box,UIAlertControllerThe size of the pop-up box is automatically adjusted based on the device size. In addition, it will return the nil value in the iPhone or the device with the tightening width. The code for configuring the pop-up box is as follows:
UIPopoverPresentationController *popover = alertController.popoverPresentationController;if (popover){ popover.sourceView = sender; popover.sourceRect = sender.bounds; popover.permittedArrowDirections = UIPopoverArrowDirectionAny;}
Pull menu effects on iPad,
UIPopoverPresentationControllerClass is also a new class in iOS 8, used to replaceUIPopoverController. At this time, the top menu is displayed in a pop-up box fixed on the Source button.
Note:UIAlertControllerThe cancel button is automatically removed when the pop-up box is used. You can click the peripheral area of the pop-up box to cancel the operation. Therefore, the cancel button is no longer required.
- Release dialog box Controller
In general, when you select an action, the Controller of the dialog box is released. However, you can still release it programmatically as needed, just like releasing other view controllers. You should remove the dialog box or pull up the menu when the application is transferred to the background runtime. Suppose we are listeningUIApplicationDidEnterBackgroundNotificationNotification message, we can release any displayed View Controller in the observer. (ReferviewDidLoadMethod ).
- (void)didEnterBackground:(NSNotification *)notification{ [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil]; [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];}
Note: To ensure operation security, we also need to ensure that all text boxes are removed.