iOS SDK: Working with UIAlertView and UIAlertViewDelegate

iOS SDK: Working with UIAlertView and UIAlertViewDelegate

Tutorial Details
  • Technology: iOS 5 SDK + Xcode 4.2
  • Difficulty: Beginner
  • Completion Time: 20 - 35 Minutes

In this tutorial you will be introduced to one of the most commonly used Cocoa-Touch classes: UIAlertView. With this class, you can quickly notify users of important or urgent application information. You may also force user feedback by combining the UIAlertView class with the UIAlertViewDelegate protocol. Read on to learn how!


Step 1: Project Setup

Create a new Xcode project using the “Single View Application” template.

UIAlertView Figure 2

Name the application “AlertDemo” and insert your own company identifier or use “com.mobiletuts.alertdemo” if you don’t have one yet. Set “iPhone” for the device family and keep the default checks. When ready, click Next.

UIAlertView Figure 2

Select a location on your hard drive to store the project and then click “Save”.

After creating your project, expand the Supporting Files folder in the Project Navigator pane to the left of the Xcode window. CTRL + Click (or right click) on the Supporting Files folder and select Add > New Group. Name the new group “images” as this is where we will store the graphics for our application.

Download the project resource file attached to this tutorial and open the “images” folder. Drag and drop all of the images into the “images” group you just created. Be sure to check “Copy items into destination group’s folder (if needed)” as this will ensure the resources are actually copied into your project and not simply linked as references. Your setup in Xcode should now look similar to this:

UIAlertView Figure 3

Step 2: Setup the Interface

Find the MainStoryboard.storyboard file in the Project Navigator and select it. You’ve just opened the storyboard for the project, which should consist of a single scene, or View Controller, that we can modify to create the interface for the application.

UIAlertView Figure 4

With the Storyboard open, the Xcode interface should now display the object library in the bottom right corner. Use the object library search box to find a UIImageView object. Place the image object on the center of the screen and manually resize it to fill the view. Next, find the image field in the attributes inspector (the attribute inspector should be in the top right portion of Xcode). Set the value for the image field to “background.png”. You should now have a nice, steel texture that fills the view controller.

UIAlertView Figure 5

Using the Object Library again, find a UIButton object and then drag that button onto the Scene. The attribute inspector should now display information for the button object. Set the type drop down field to “custom”. Next, set the image field to “button.png”. You should now see the button image on the scene view controller, but it probably doesn’t look right. With the button object selected, you’ll need to select Editor > Size to Fit Content in order to automatically resize the button bounds to the size of the image content. Next, center the button in the screen by dragging it toward the middle.

You should now have the button configured correctly for the default state, but we want to display a different image when the button is actually being pressed. Change the state config drop down value to “highlighted”. The changes you make in the attributes inspector now will apply only to the highlighted state. Set the image attribute for the highlighted button state to button-pressed.png. Your Storyboard should now look like this:

UIAlertView Figure 6

This is a good time to test your progress, so save your work ( File > Save) and then run the project in the iPhone simulator (Product > Run). You should now be able to tap the button and see the image change in the simulator.


Step 3: Create the Alert Method

With the project storyboard still open, click the “Show the Assistant Editor” button near the top right of the Xcode window to display the source code listing for ViewController.h. From this perspective, hold down both the Control (CTRL) button and the mouse button (the left mouse button if your mouse has two) over the button object in the Storyboard scene, and then drag into the source code listing, just above the @end line.

Figure 7

A new dialogue box will open that will automatically create a connection between the interface element and your view controller class. From this popup you can create outlets or actions. Outlets are used to create properties that reference your Interface Builder objects, and actions are used to connect methods to IB object actions.

Select “Action” from the connection drop down, enter “showMessage” as the connection name, and then click Connect. Interface Builder should have just added the following line to your ViewController.h file:

- (IBAction)showMessage:(id)sender;

In addition, ViewController.m should now have this method definition:

- (IBAction)showMessage:(id)sender {
}

When the user taps the button, the code in this method will be executed. That means we’re finally ready to dig into the code for displaying a UIAlertView and responding to its delegate methods!


Step 4: Create a Basic Alert Message

Now that you have your project template setup, you are ready to use UIAlertView to trigger your message when the custom button is pressed. Open the ViewController.m file, and type the following into the showMessage method you created earlier:

- (IBAction)showMessage:(id)sender {
    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Hello World!"
                                                      message:@"This is your first UIAlertview message."
                                                     delegate:nil
                                            cancelButtonTitle:@"OK"
                                            otherButtonTitles:nil];
    [message show];
}

Above you are creating and initializing your instance of the UIAlertView class. The initWithTitle: and message: parameters are self-explanatory and easily understood after seeing an alert displayed. The delegate: parameter refers to which class should receive delegate notification messages for the UIAlertViewDelegate (demonstrated later). The cancelButton: parameter is the default button to be displayed along with the alert, and the otherButtonTitles: parameter is used to display one or multiple additional options that the user may select.

After creating an alert object, the [message show] call actually shows our message by popping our new UIAlertView onto the screen.

If you build and debug the application now, you’ll see that tapping the button results in our message being displayed!

UIAlertView Figure 8

NOTE: If nothing happens when you tap the button in the simulator, be sure that you have actually saved the changes you made in the Storyboard file and that the “Touch up inside” action is connected to the showMessage: method.


Step 5: Add Buttons to the Alert

Adding additional buttons to a UIAlertView can be done either when you initialize your object or anytime after. To add buttons at initialization time in the code above, you would simply modify the showMessage: method like so:

    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Hello World!"
                                                      message:@"This is your first UIAlertview message."
                                                     delegate:nil
                                            cancelButtonTitle:@"Button 1"
                                            otherButtonTitles:@"Button 2", @"Button 3", nil];
    [message show];

To add buttons after having initialized your alert, you would use the following lines of code:

       UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Hello World!"
                                                                                  message:@"This is your first UIAlertview message."
                                                                                  delegate:nil
                                                                    cancelButtonTitle:@"Button 1"
                                                                    otherButtonTitles:nil];
        [message addButtonWithTitle:@"Button 2"];
        [message addButtonWithTitle:@"Button 3"];
        [message show];

Both of these code fragments are equivalent, but using the addButtonWithTitle: method makes it easy to conditionally add buttons to your alerts, perhaps by wrapping them in if statements.


Step 6: Respond to Alert Button Selection

Switch back to ViewController.h and modify your class declaration line to read as follows:

@interface ViewController : UIViewController <UIAlertViewDelegate> {

This allows your class to respond to the UIAlertViewDelegate protocol methods. In order to respond to button taps in our UIAlertView, we will use the – alertView:clickedButtonAtIndex: protocol method. Back in ViewController.m, add this into your class:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
}

As you can see from the method name, this method will accept a pointer to the UIAlertView object we created earlier and the button index that was selected by the user. You may be tempted to simply switch conditionally on the buttonIndex variable to determine which button was selected by the user, but what would happen if you were conditionally adding buttons to the alert? In that scenario, the button with index 1 might not always be the one you want. A much better way is to test against the title of the button and then act accordingly, like so:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
	if([title isEqualToString:@"Button 1"])
	{
		NSLog(@"Button 1 was selected.");
	}
	else if([title isEqualToString:@"Button 2"])
	{
		NSLog(@"Button 2 was selected.");
	}
	else if([title isEqualToString:@"Button 3"])
	{
		NSLog(@"Button 3 was selected.");
	}
}

There is one more tweak that we need to make before this will work. Go back to the UIAlertView initialization statement, and update the delegate: parameter to accept the self keyword instead of nil. After doing so, the code block should look like this:

    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Hello World!"
                                                      message:@"This is your first UIAlertview message."
                                                     delegate:self
                                            cancelButtonTitle:@"Button 1"
                                            otherButtonTitles:@"Button 2", @"Button 3", nil];
    [message show];

If you build and debug the application now, you should be able to select multiple buttons and see a statement print to the console when a button is selected (need help finding the console? Select View > Debug Area > Activate Console from the Xcode menu).

This is what the final alert view should look like in the simulator:

Figure 9

Conclusion

This concludes our introductory tutorial on UIAlertView. In addition to what we covered today, there are many other options provided by the UIAlertViewDelegate protocol and, with the release of iOS 5, some additional ways to use UIAlertView. If you would like to see an additional tutorial on these advanced alert view topics, let me know in the comments section below! Also feel free to send in questions or comments via either my personal twitter @markhammonds or the official Mobiletuts+ twitter account @envatomobile.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Luan

    Nice and informative! Thanks!

  • http://labs.dariux.com Dario Gutierrez

    Great dude, for me is an excellent tut ’cause I am a novice in this field and is very useful. congratulations.

  • http://mobile.tutsplus.com Mark Hammonds
    Author

    @Luan, @Dario Thanks! Glad to hear the tutorial was useful. In the future we will likely follow up with another tutorial covering additional ways to use UIAlertViewDelegate and to prompt the user for text in an alert.

  • Paul

    Thanks for the tutorial! I love this site and reading how different people explain iOS programming. Yes I’d like to see a tutorial on using UITextField as a subview of the alert .

  • Oday Yousif

    Please more tutorials

  • http://thoughtsunlimited.net Ashwin

    Awesome tutorial! This is a third tutorial in a line I am completing – after setting up xcode on my Mac.
    Great job and a great site!

  • moose

    i’m new to iPhone programing could some one please explain to me what this line of code does?

    thanks

    • Susan

      What line of code?

  • Avinash

    Thanks.
    It helped me.

  • keith

    Man, I had been looking for this for a week. This is ALL i need for the moment. Thanks for providing the source code. Keep up the good work!

  • http://www.leicesterwebdesigner.com Mayuir

    Hi,

    Thanks for the tutorial. Im using Xcode 4 and came across a bit of a problem, so if anyone else is having the same problem, here is the solution.

    Problem: alertView:clickedButtonAtIndex: protocol method not bring called.

    Solution: change “delegate” in the UIAlertView *message instance to “delegate:self”, and it works.

    Hope that helps.

    • http://mobile.tutsplus.com Mark Hammonds
      Author

      Hey Mayuir,

      Thanks for your feedback! Glad to hear you were able to get the tutorial working.

      In one of the last paragraphs, I actually do point out that you’ll need to set the delegate to self:

      “Think this code will run correctly? Actually, there is one more tweak that we need to make. Go back to the UIAlertView initialization statement, and update the delegate: parameter to accept the self keyword instead of nil.”

      However, in retrospect, I can see how it would be easy for someone to miss that line of the text. Also, thanks for pointing out that this tutorial needs to be updated to Xcode 4. I’ll be sure to add it to the revision list!

      Best Regards,
      Mark Hammonds

  • Mayuir

    Yes, you’re quite right Mark … I missed that line totally. Apologies.

    Mayuir

    • http://mobile.tutsplus.com Mark Hammonds
      Author

      No worries, thanks to your feedback I was able to make that step more explicit!

  • huss

    great!

  • http://www.islamiceventfinder.com Islamic Event Finder

    I really wish there are more of these tuts targeting the latest Xcode and the latest iOS. Things have changed a bit with the latest Xcode and iOS and so some of the older tuts are not much useful anymore. If the awesome guys like you can pump out more tuts on these latest stuff that would help a lot. Just my $0.02.

  • http://iphonepacking.com Hamid

    Tnx
    it was so useful for me,

  • http://wrey75.wordpress.com William

    Hi,

    The button text is “OK” but I suppose you can get the right text for the button. I mean “YES” or “CANCEL” in english, “OUI” or “ANNULER” in French and so on. But I do not not find such method to do so in IOS. Perhaps do you have an idea? Because the way you display the alert is good but the button text should be compatible with the user language.

    I am quite surprised you have to put your own “hard-coded” text because Windows SDK (for example) has simple constants for CANCEL, OK, RETRY and you don’t have to bother about the translation: it is done by the system itself (transparently).

  • http://www.kobbleit.com pkuhns

    Thank you for posting this tutorial – I really appreciate it.

    Newbies like me aren’t sure WHERE stuff goes, let alone how to type it properly. This tutorial was a huge help showing us WHERE we are supposed to put different snippets of code. I’m still trying to get a hang of the syntax (confusing is not really a strong enough word), but also trying to understand why some things go in the .h file and other stuff goes in .m / appdelegate.h / etc.

    The education continues…

  • http://www.potsdam.com Jason

    This is excellent. Please create more tutorials of this quality.

    Jason

  • Mehmood

    Nice man! Awsummm

  • Francisco

    Nice job! You really help me a lot with this tips!

    It was so useful and simply… Thanks

  • http://www.marigotgroup.com Greg

    Lifesaver. Beating my head against to wall all evening trying to get this to work, while searching all over the net. Finally worked after finding your tutorial. Keep up the good work!

    BTW — will this work if I have more than one alert in a class? Is there a way to differentiate the alertView DismissWithIndex ‘trap’ routine to service different UIAlertView instances?

  • Salman

    Very informative and helpful tutorial… :-)

  • http://www.goinspired.com Go Inspired

    Cool tutorial! Thanks for the information!

  • Metavirulent

    Found so many tutorials showing code that causes memory issues lately and this is no exception. Some release objects they are not supposed to release and some fail to release memory correctly. This tutorial is one of the latter. Not been reading it all but a quick heads-up, Section 4 onwards, all code examples fail to properly release the UIAlertView object and therefore result in memory leaks.

    Either add a release or use autorelease during allocation to fix it.

    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@”Hello World!”
    message:@”This is your first UIAlertview message.”
    delegate:nil
    cancelButtonTitle:@”OK”
    otherButtonTitles:nil];

    [message show];
    [message release];

    • http://mobile.tutsplus.com Mark Hammonds
      Author

      Hi Meta,

      This tutorial uses Automatic Reference Counting (ARC), and consequently any needed release statements are added automatically at compile time. In fact, not only is the code you’ve suggested above unnecessary, it will actually result in a compile-time error with ARC enabled.

      To learn more about ARC and why so much of the code you’re seeing these days no longer uses Manual Reference Counting, check out the official Apple docs:

      http://developer.apple.com/library/mac/#releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html

      -Mark

  • MK

    I want to create dialog box from xib file. How can we do that?

  • Rija

    This code uses “storyboard” which is a new feature of iOS 5, isn’t it?

    According to my experience, application using storyboard does not work with iOS 4 and iOS 3 (iPhone 4, 3GS and less)? And yet, still 90% of the population in the world don’t migrate yet to iOS 5!

    • Andy

      This tutorial is not storyboard dependent at all. It does use ARC, which can be used back through iOS 4.

  • Dale Magnin

    thanks….GREAT help!

  • Augusto Nizzo Mc Intosh

    What happens with memory? Shouldn’t you add some releases?

  • Stav

    Great tutorial Mark. Recently I decided that the whole delegation thing isn’t so necessary to handle alerts so I created a nice opensource solution: https://github.com/stavash/UIBAlertView This is in fact a UIAlertView with block callbacks.

  • Ankur Gupta

    Thanks!!!!!!!!!!

  • tcm692

    Can you add onto this tutorial? Maybe by showing how to link from a button to an event…for example, sending an email when Button 2 or 3 are pressed?

  • http://twitter.com/daronwolff Cuauhtémoc Solís

    Thanks Many Thanks