Using Uialertcontroller in iOS 8

Source: Internet
Author: User

When using the Action form (action sheet) in iOS8, I found that uiactionsheet on Xcode crossed a line, prompting: " UIAlertView is deprecated. Use UIAlertController  witha preferredStyle of UIAlertControllerStyleAlert instead."

Originally in the IOS8, Uialertview, Uiactionsheet (and their respective delegate protocols) had been discarded,

Therefore, if you want to implement an action form (action sheet) or a warning view (alert), you need to use Uialertcontroller to replace and implement Uialertview and Uiactionsheet functions.

The following blog post, which describes how to use Uialertcontroller very well:

Transferred from: HTTP://WWW.JIANSHU.COM/P/86F933850DF8

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. The new Uipresentationcontroller plays an important role in achieving transition animations between view controllers and adaptive device size changes, such as rotation, which effectively saves programmers ' workload (heaven Knows). Also, some of the old Uikit controls have also undergone many changes, such as alert views, Action Sheets, popovers, and search Bar Controllers. This article will be a general introduction to the changes in alert views and action sheets, and we will use OBJECTIVE-C and Swift in two languages for code descriptions.

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.

Objective-c version:

1 Uialertview *alertview = [[Uialertview alloc] initwithtitle:@ "title" message:@ "This is the default style of Uialertview" delegate:self cancelbuttontitle:@ "Cancel" otherbuttontitles:@ "good", nil];2 [Alertview show];

Unlike the swift version and the objective-c version, in Swift, the initialization of Alertview only allows the creation of a dialog view with a Cancel button. Perhaps you can see the Init method with Otherbuttontitles, but unfortunately, there is no way to compile this method.

1 var alertview = Uialertview (title: "caption", message: "This is the default style for Uialertview", Delegate:self, Cancelbuttontitle: "Cancel") 2 alert View.show ()

Swift version of Uialertview

To be able to create the same dialog view as the Objective-c version above, we can take the curve of saving the nation, although it is troublesome, but we can do anything for the purpose, right?

1 var alertview = Uialertview () 2 alertview.delegate = self3 Alertview.title = "title" 4 Alertview.message = "This is the default for Uialertview Style "5 Alertview.addbuttonwithtitle (" Cancel ") 6 Alertview.addbuttonwithtitle (" good ") 7 alertview.show ()

You can also implement the effect of entering text, passwords, and even login boxes by changing the Alertviewstyle property of the Uialertview.

Uialertview Text dialog box

Uialertview Password dialog box

Uialertview Login dialog box

The Uialertviewdelegate protocol has a callback method that responds to the button action of the dialog view. And when the text box content changes, call the Alertviewshouldenableotherbutton: method to make the button dynamically available or unavailable.

To illustrate, Apple is now not advocating the use of Uialertview in iOS 8, instead of Uialertcontroller. Let's introduce how to use Uialertcontroller.

Uialertcontroller

In iOS 8, Uialertcontroller is functionally the same as Uialertview and Uiactionsheet, and Uialertcontroller replaces the functionality and function of these two goods in a modular way. 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, and the code that creates the underlying uialertcontroller is very similar to the code that creates the Uialertview:

Objective-c version:

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

Swift version:

1 var alertcontroller = Uialertcontroller (title: "caption", message: "This is the default style for Uialertcontroller", Preferredstyle: Uialertcontrollerstyle.alert)

We do not need to specify a proxy as compared to creating uialertview, and we do not need to specify a button during initialization. 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 an instance of Uialertaction, you can add an action button to the controller. Uialertaction consists of a header string, a style, and a block of code that runs when the user selects the action. With Uialertactionstyle, you can choose from the following three action styles: general (default), cancellation (cancel), and alert (destruective). To achieve the button effect we created when we created Uialertview, we simply created these two action buttons and added them to the controller.

Objective-c version:

1 uialertaction *cancelaction = [uialertaction actionwithtitle:@ "Cancel" Style:uialertactionstylecancel handler:nil];2 Uialertaction *okaction = [uialertaction actionwithtitle:@ "Good" Style:uialertactionstyledefault handler:nil];3 [ Alertcontroller addaction:cancelaction];4 [Alertcontroller addaction:okaction];

Swift version:

1 var cancelaction = uialertaction (title: "Cancel", Style:UIAlertActionStyle.Cancel, Handler:nil) 2 var okaction = Uialertact Ion (title: "Good", Style:UIAlertActionStyle.Default, Handler:nil) 3 alertcontroller.addaction (cancelaction) 4 Alertcontroller.addaction (okaction)

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

Objective-c version:

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

Swift version:

Self.presentviewcontroller (Alertcontroller, Animated:true, 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 O NE 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.

Objective-c version:

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

Swift version:

1 var resetaction = uialertaction (title: "Reset", Style:UIAlertActionStyle.Destructive, Handler:nil) 2 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

Uialertcontroller's great flexibility means you don't have to stick to the built-in style. Previously we could only choose from the default view, text box view, Password box view, login and password input box view, and now we can add any number of Uitextfield objects to the dialog box, and we can use all the Uitextfield features. 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.

Objective-c version:

1 Uialertcontroller *alertcontroller = [uialertcontroller alertcontrollerwithtitle:@ "Text Dialog" message:@ "Login and Password dialog box example" preferredstyle:uialertcontrollerstylealert];2 [Alertcontroller addtextfieldwithconfigurationhandler:^ ( Uitextfield *textfield) {3     Textfield.placeholder = @ "Login"; 4}];5 [Alertcontroller addtextfieldwithconfigurationhandler:^ (Uitextfield *textfield) {6     Textfield.placeholder = @ "password"; 7     Textfield.securetextentry = yes;8}];

Swift version:

1 Alertcontroller.addtextfieldwithconfigurationhandler {2 (textfield:uitextfield!), Void in3     Textfield.placeholder = "Login" 4}5 alertcontroller.addtextfieldwithconfigurationhandler {6 (textfield:uitextfield!)- > Void in7     textfield.placeholder = "Password" 8     textfield.securetextentry = true9}

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

Objective-c version:

1 uialertaction *okaction = [uialertaction actionwithtitle:@ "Good" Style:uialertactionstyledefault handler:^ ( Uialertaction *action) {2     Uitextfield *login = alertcontroller.textfields.firstobject;3     UITextField * Password = alertcontroller.textfields.lastobject;4 ...     5}];

Swift version:

1 var okaction = uialertaction (title: "Good", Style:UIAlertActionStyle.Default) {2 (action:uialertaction!), Void in3< C3/>var login = Alertcontroller.textfields?. First as UITextField4     var password = alertcontroller.textfields?. Last as UITextField5}

If we want to implement the delegate method in Uialertview Alertviewshouldenableotherbutton: The method can be somewhat complicated. Suppose we want to have at least 3 characters in the Login text box to activate the OK button. Unfortunately, there is no corresponding delegate method in Uialertcontroller, 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.

Objective-c version:

1 [Alertcontroller addtextfieldwithconfigurationhandler:^ (Uitextfield *textfield) {2     ... 3     [[Nsnotificationcenter defaultcenter] addobserver:self selector: @selector (alerttextfielddidchange:) Name: Uitextfieldtextdidchangenotification object:textfield];4}];

Swift version:

1 Alertcontroller.addtextfieldwithconfigurationhandler {2 (textfield:uitextfield!), Void in3     ... 4     Nsnotificationcenter.defaultcenter (). Addobserver (Self, Selector:selector ("Alerttextfielddidchange:"), name : Uitextfieldtextdidchangenotification, Object:textfield) 5}

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:

Objective-c version:

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

Swift version:

1 Alertcontroller.addtextfieldwithconfigurationhandler {2 (textfield:uitextfield!), Void in3     ... 4     Nsnotificationcenter.defaultcenter (). Addobserver (Self, Selector:selector ("Alerttextfielddidchange:"), name : Uitextfieldtextdidchangenotification, Object:textfield) 5}

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:

Objective-c version:

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

Swift version:

1 var okaction = uialertaction (title: "Good", Style:UIAlertActionStyle.Default) {2 (action:uialertaction!), Void in3< c2/> ... 4     Nsnotificationcenter.defaultcenter (). Removeobserver (self, name:uitextfieldtextdidchangenotification, Object:nil) 5}

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

Objective-c version:

1 okaction.enabled = NO;

Swift version:

1 okaction.enabled = False

Next, in the Notification Viewer (notification observer), we need to check the contents of the Login text box before activating the button state.

Objective-c version:

1-(void) Alerttextfielddidchange: (nsnotification *) notification{2     uialertcontroller *alertcontroller = ( Uialertcontroller *) self.presentedviewcontroller;3     if (alertcontroller) {4         Uitextfield *login = Alertcontroller.textfields.firstobject;5         uialertaction *okaction = alertcontroller.actions.lastobject;6         okaction.enabled = login.text.length > 2;7     }8}

Swift version:

1 func alerttextfielddidchange (notification:nsnotification) {2     var alertcontroller = Self.presentedviewcontroller as Uialertcontroller?3     if (alertcontroller! = nil) {4         var login = Alertcontroller !. Textfields?. First as UITextField5         var okaction = alertcontroller!. Actions.last as UIAlertAction6         okaction.enabled = countelements (login.text) >     }8}

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.

Objective-c version:

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

Swift version:

1 var alertcontroller = Uialertcontroller (title: "Save or delete data", message: "Delete data will not be recoverable", Preferredstyle: Uialertcontrollerstyle.actionsheet)

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

Objective-c version:

1 uialertaction *cancelaction = [uialertaction actionwithtitle:@ "Cancel" Style:uialertactionstylecancel handler:nil];2 Uialertaction *deleteaction = [uialertaction actionwithtitle:@ "Delete" style:uialertactionstyledestructive Handler:nil]; 3 Uialertaction *archiveaction = [uialertaction actionwithtitle:@ "Save" Style:uialertactionstyledefault handler:nil];4 [ Alertcontroller addaction:cancelaction];5 [Alertcontroller addaction:deleteaction];6 [AlertController addAction: Archiveaction];

Swift version:

1 var cancelaction = uialertaction (title: "Cancel", Style:UIAlertActionStyle.Cancel, Handler:nil) 2 var deleteaction = Uialer Taction (title: "Delete", Style:UIAlertActionStyle.Destructive, Handler:nil) 3 var archiveaction = uialertaction (title: "Save" , Style:UIAlertActionStyle.Default, Handler:nil) 4 alertcontroller.addaction (cancelaction) 5 Alertcontroller.addaction (deleteaction) 6 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.

Objective-c version:

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

Swift version:

1 Self.presentviewcontroller (Alertcontroller, Animated:true, 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 all "destroy" style buttons to be ranked number one (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 a regular uibutton to trigger the pull-up menu, we'll use it as a stroke.

In iOS 8, we no longer have to carefully calculate the size of the popup, Uialertcontroller will adapt to the size of the popup box based on 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:

Objective-c version:

1 Uipopoverpresentationcontroller *popover = alertcontroller.popoverpresentationcontroller;2 if (popover) {3     Popover.sourceview = sender;4     popover.sourcerect = sender.bounds;5     popover.permittedarrowdirections = UIPOPOVERARROWDIRECTIONANY;6}

Swift version:

1 var popover = Alertcontroller.popoverpresentationcontroller2 if (popover! = nil) {3     popover?. Sourceview = Sender4     popover?. Sourcerect = Sender.bounds5     popover?. Permittedarrowdirections = Uipopoverarrowdirection.any6}

Pull-up menu effect on ipad

The Uipopoverpresentationcontroller class is also the new class that appears in iOS 8 to replace the Uipopovercontroller. This time the pull-up menu is displayed as a popup box fixed on the source button.

Note that Uialertcontroller automatically removes the Cancel button 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 displayed view controller in Observer. (Refer to the example code that establishes observer in the Viewdidload method).

Objective-c version:

1-(void) Didenterbackground: (nsnotification *) notification2 {3   [[Nsnotificationcenter Defaultcenter] Removeobserver:self name:uitextfieldtextdidchangenotification object:nil];4   [Self.presentedviewcontroller Dismissviewcontrolleranimated:no Completion:nil];5}

Swift version:

1 func didenterackground (notification:nsnotification) {2     nsnotificationcenter.defaultcenter (). RemoveObserver ( Self, name:uitextfieldtextdidchangenotification, Object:nil) 3     Self.presentedviewcontroller? Dismissviewcontrolleranimated (False, Completion:nil) 4}

Note that to ensure safe operation we also want to make sure that all text box observer are removed.

Let's summarize.

This article is long, but hopefully it will help you. The original Uialertview and Uiactionsheet classes can still work well in iOS 8, so there's no need to rush to change the code (you know that many of the functions used in this article are supported in iOS 8).

Using Uialertcontroller in iOS 8

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.