Between Ios--uialertview and Uialertcontroller and uialertaction.

Source: Internet
Author: User

One of the new features of IOS 8 is that the interface is more adaptable and flexible, so many view controller implementations have changed dramatically. Brand-New UIPresentationControllerIt plays an important role in implementing transition animations between view controllers and adaptive device size changes, such as rotation, which effectively saves the programmer's workload (heaven Knows). Also, some of the old UIKitControls have also undergone a number of changes, such as Alert ViewsActionSheetsPopoversAnd Search Bar Controllers。 This article will Alert ViewsAnd Action SheetsA general introduction to the changes that took place, using objective-c
    • Uialertview
With Apple's last release of iOS 5, the dialog view style appeared before us, and until now it has not changed much. The following code snippet shows how to initialize and display a dialog view with a "Cancel" and "OK" button.
Uialertview *alertview = [[Uialertview alloc] initwithtitle:@ "title" message:@ "This is the default style for Uialertview" delegate:self cancelbuttontitle:@ "Cancel" otherbuttontitles:@ "good", nil]; [Alertview show];
default style for Uialertview

To be able to create the same view of the dialog box as above

var Alertview = Uialertview () alertview.delegate = Selfalertview.title = "title" Alertview.message = "This is the default style for Uialertview" Alertview.addbuttonwithtitle ("Cancel") Alertview.addbuttonwithtitle ("Good") alertview.show ()

You can also change UIAlertView the alertViewStyle properties to achieve the effect of entering text, passwords, or even login boxes.


Uialertview Text dialog box
Uialertview Password dialog box
Uialertview Login dialog box

UIAlertViewDelegateThe protocol has a callback method that responds to the button action of the dialog view. Also, when the contents of a text box change, the calling alertViewShouldEnableOtherButton: method can make the button dynamically available or unavailable.

To illustrate, Apple is now not advocating the use of iOS 8 UIAlertView , instead UIAlertController . Here UIAlertController 's how to use this.

    • Uialertcontroller

In iOS 8, UIAlertController functionally and UIAlertView as well as UIActionSheet the same, in UIAlertController a modular replacement way to replace the two goods function and function. Whether you use the dialog box (alert) or the pull-up menu (action sheet) depends on how you set the preferred style when you create the controller.

    • A simple example of a dialog box

You can compare the two different code that creates the dialog box, creating the underlying UIAlertController code and creating UIAlertView the code very similar:

Uialertcontroller *alertcontroller = [Uialertcontroller alertcontrollerwithtitle:@ "title" message:@ " This is the default style of Uialertcontroller "Preferredstyle:uialertcontrollerstylealert";

We do UIAlertView not need to specify a proxy or specify a button during initialization when compared to the creation process. However, pay special attention to the third parameter, to determine whether you are choosing a dialog box style or a pull-up menu style.

By creating UIAlertAction An instance, you can add an action button to the controller. Consists UIAlertAction of a header string, a style, and a block of code that runs when the user selects the action. UIAlertActionStyleyou can choose from the following three action styles: general (default), cancellation (cancel), and alert (destruective). To achieve the button effect we created at the UIAlertView time of creation, we simply created these two action buttons and added them to the controller.

Uialertaction *cancelaction = [uialertaction actionwithtitle:@ "Cancel" Style:uialertactionstylecancel Handler:nil]; Uialertaction *okaction = [uialertaction actionwithtitle:@ "good" style:uialertactionstyledefault Handler:nil]; [Alertcontroller addaction:cancelaction]; [Alertcontroller addaction:okaction];

Finally, we just need to show this dialog view controller:

[Self Presentviewcontroller:alertcontroller animated:yes completion:nil];

Uialertcontroller Default Style

The order in which the buttons are displayed depends on the order in which they are added to the dialog box controller. In general, according to Apple's official IOS user interface Guide, in a dialog box with two buttons, you should leave the Cancel button on the left. Note that the Cancel button is unique , and if you add a second Cancel button, you will get a run-time exception like this:

* Terminating app due to uncaught exception ' nsinternalinconsistencyexception ', Reason: ' Uialertcontroller can only has one Action with a style of Uialertactionstylecancel '

The exception information is concise and clear, we will not repeat it here.

    • "Alert" style

What is the "alert" style? Let's not worry about answering this question first, let's take a look at the following simple example of the "alert" style. In this example, we replace the "good" button in the previous example with the "Reset" button.

Uialertaction *resetaction = [uialertaction actionwithtitle:@ "reset" style:uialertactionstyledestructive Handler:nil]; [Alertcontroller addaction:resetaction];

"Alert" style

As you can see, the "Reset" button we added turns red. According to Apple's official definition, "alert"-style buttons are used for actions that may change or delete data. So a red eye-catching logo is used to alert the user.

    • Text dialog box

UIAlertControllerGreat flexibility means you don't have to stick to the built-in style. Previously we could only select in the default view, text box view, Password box view, login and password input box view, and now we can add any number of objects to the dialog box UITextField , and we can use all the UITextField attributes. When you add a text box to a dialog controller, you need to specify a block of code to configure the text box.

Give me a chestnut. To reestablish the original login and Password Style dialog box, we can add two text boxes to them, configure them with the appropriate placeholders, and finally set the password input box to use secure text input.

Uialertcontroller *alertcontroller = [uialertcontroller alertcontrollerwithtitle:@ "Text dialog box" message:@ "Login and Password Dialog example" Preferredstyle:uialertcontrollerstylealert]; [Alertcontroller addtextfieldwithconfigurationhandler:^ (Uitextfield *textfield) {    Textfield.placeholder = @ "login";}]; [Alertcontroller addtextfieldwithconfigurationhandler:^ (Uitextfield *textfield) {    Textfield.placeholder = @ "password";    Textfield.securetextentry = YES;}];

When the "good" button is pressed, we let the program read the value in the text box.

Uialertaction *okaction = [uialertaction actionwithtitle:@ "Good" Style:uialertactionstyledefault handler:^ ( Uialertaction *action) {    Uitextfield *login = alertController.textFields.firstObject;    Uitextfield *password = AlertController.textFields.lastObject;
NSLog (@ "account number:%@", Login.text);
NSLog (@ "Password:%@", Password.text);
}];

If we want to implement UIAlertView the method of the delegate method alertViewShouldEnableOtherButton: , there may be some complications. Suppose we want to have at least 3 characters in the Login text box to activate the OK button. Unfortunately, UIAlertController there is no corresponding delegate method in, so we need to add a observer to the Login text box. The Observer pattern defines a one-to-many dependency between objects, and when an object's state changes, all objects that depend on it are notified and automatically updated. We can add the following code snippet to the construction code block to implement.

[Alertcontroller addtextfieldwithconfigurationhandler:^ (Uitextfield *textfield) {    ...    [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (alerttextfielddidchange:) Name: Uitextfieldtextdidchangenotification Object:textfield];}];

We need to remove this observer when the view Controller is released, and we can implement it by adding the appropriate code in the handler block of code for each button action (as well as any other place where the view controller might be released). For example, in okaction this button action:

Uialertaction *okaction = [uialertaction actionwithtitle:@ "Good" Style:uialertactionstyledefault handler:^ ( Uialertaction *action) {    ...    [[Nsnotificationcenter Defaultcenter] removeobserver:self name:uitextfieldtextdidchangenotification object:nil];}];

We want to freeze the "OK" button before the dialog box is displayed.

okaction.enabled = NO;
Next, in the Notification Viewer (notification observer), we need to check the contents of the Login text box before activating the button state.
-(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;    }}

Uialertcontroller Example of Login and Password dialog box

OK, now the "good" button in the dialog box is frozen unless you enter more than 3 characters in the "Login" text box:

    • Pull-up menu

The pull-up menu can be useful when you need to show users a range of choices (choose a phobia killer). Unlike dialog boxes, the display of the pull-up menu is related to the size of the device. On the iphone (tighten the width), the pull-up menu rises from the bottom of the screen. On the ipad (general width), the pull-up menu is displayed as a popup box.

The way you create a pull-down menu is very similar to the way you create a dialog box, except that the only difference is their form.

Uialertcontroller *alertcontroller = [Uialertcontroller alertcontrollerwithtitle:@ "Save or delete data" message:@ "delete data will not be recoverable" Preferredstyle:uialertcontrollerstyleactionsheet];

The button action is added in the same way as the dialog box.

Uialertaction *cancelaction = [uialertaction actionwithtitle:@ "Cancel" Style:uialertactionstylecancel Handler:nil]; Uialertaction *deleteaction = [uialertaction actionwithtitle:@ "Delete" style:uialertactionstyledestructive Handler:nil]; Uialertaction *archiveaction = [uialertaction actionwithtitle:@ "Save" Style:uialertactionstyledefault Handler:nil]; [Alertcontroller addaction:cancelaction]; [Alertcontroller addaction:deleteaction]; [Alertcontroller addaction:archiveaction];

You cannot add a text box to the pull-down menu, and if you forcibly add a text box, you will be honored to get a run-time exception:

* Terminating app due to uncaught exception ' nsinternalinconsistencyexception ', Reason: ' Text fields can only is added to an Alert controller of Style Uialertcontrollerstylealert '

Similarly, the simple exception description, we do not say much.

Next we'll be able to show on the iphone or any other device with a tighter width, and it's not going to work out as well as we expected.

[Self Presentviewcontroller:alertcontroller animated:yes completion:nil];

Pull-up menu effect on iphone

If there is a "cancel" button in the pull-down menu, it will always appear at the bottom of the menu, regardless of the order in which it was added (and so willful). The other buttons will be displayed sequentially from top to bottom in the order in which they were added. The IOS user interface Guide requires that all warning style buttons must be ranked first (target homing, well understood, right?). )。

Don't get too excited, we still have a very serious problem, and the problem is more hidden. When we use an ipad or other general-width device, we get a runtime exception:

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 earlier, on a regular-width device, the pull-up menu is displayed as a popup box . The popup must have a stroke (anchor point) that can be a source view or a column button item. Since in this case we used regular UIButton to trigger the pull-up menu, we'll use it as a stroke.

In iOS 8 we no longer have to be careful to calculate the size of the popup, which UIAlertController will fit the size of the popover according to the device size. And it will return a nil value on the iphone or a device with a tighter width. The code to configure the popup is as follows:

123456 UIPopoverPresentationController *popover = alertController.popoverPresentationController;if(popover){    popover.sourceView = sender;    popover.sourceRect = sender.bounds;    popover.permittedArrowDirections = UIPopoverArrowDirectionAny;}

The pull-up menu effect on the ipad,

UIPopoverPresentationControllerClass is also a new class that appears in iOS 8 for replacement UIPopoverController . This time the pull-up menu is displayed as a popup box fixed on the source button.

Be careful to UIAlertController remove the Cancel button automatically when using the popup box. The user cancels the action by tapping the outer part of the PopOver, so the Cancel button is no longer necessary.

    • To release the dialog box controller

Normally, the dialog controller will release itself when the user selects an action. However, you can still release it programmatically when you need it, just as you would release other view controllers. You should remove the dialog box or the pull-down menu when the application goes to the background runtime. Assuming we are listening for UIApplicationDidEnterBackgroundNotification notification messages, we can release any view controller that is displayed in observer. (Refer to the viewDidLoad example code that establishes observer in the method).

-(void) Didenterbackground: (nsnotification *) notification{  [[Nsnotificationcenter Defaultcenter] Removeobserver:self name:uitextfieldtextdidchangenotification Object:nil];  [Self.presentedviewcontroller Dismissviewcontrolleranimated:no completion:nil];}
Note that to ensure safe operation we also want to make sure that all text box observer are removed.

Between Ios--uialertview and Uialertcontroller and uialertaction.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.