iOS 5 | How To Use the UIAlertView in iPad or iPhone Application

The UIAlertView is much more that a simple alert popover, which it does very smartly. The UIAlertView can be enhanced to be used as an input form as well. You can add custom buttons and other design elements that direct users, display important information, capture information from users and more.

This tutorial will show to develop and customize the UIAlertView programmatically. The UIAlertView is a specialized UIView in the Cocoa Touch API. It is intended to be used as is and cannot be or shouldn’t subclassed. The API is flexible enough that you don’t need to subclass it to create a popover panel for your app.

The API

– initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles:
The initWithTitle method can be used to create a simple UIAlertView popover that displays either an error message or a warning or even a notification.

  • The message parameter is a standard NSString object. You can pass the NSString object literally or as an instance variable. I find using an instance variable much easier when I need to concatenate another string object, say like an NSError message detail then passing the NSString to the message argument.
  • The delegate argument is the receiverès delegate, like self, or nil if there is no delegate
  • The cancelButtonTitle means that you provide a title for the button that dismisses the UIAlertView and possibly return a value. This can be “Yes” or “Cancel” or “OK” or “Whatever you like”.
  • The otherButtonTitles is a NSString value but you can define several individual buttons separated by a comma

You could also set the UIAlertview properties individually using the individual properties included in the API. Let us look at the properties that are included in the API and that you can use to personalize the UIAlertView:

  • delegate

The delegate property is used to establish the receiver’s delegate, like for instance self. You can also specify nil if there is no delegate. The delegate is used to notify or to pass information to another other that the calling object has done something. A bit like an event.

  • message

The message property is a simple or complex NSString value. By complex I mean that you can concatenate and do other string manipulations. I find that it is best to define the NSString variable separately and then pass the value to the message property.

  • alertViewStyle

The alertWithStyle is used to determine what kind of display your UIAlertView has displayed.

  • title

The title property is the name in the title bar. This is handy to inform the user the type of alert you are displaying. For instance “Error!” or “Warning”, or “Success”.

  • visible

The visible attribute is a read only boolean value indicating if the receiver or UIAlertView is visible or not.

  • addButtonWithTitle

This property will had a button to the UIAlertView and label it. You can use this property to add several buttons.

  • numberOfButtons

This attribute indicates the number of buttons that are displayed

  • buttonTitleAtIndex

This attribute sets the title of a button in an array of buttons at position indicated by Index

  • textFieldAtIndex

This attribute gets the field at the specified index. This also assigns the value that was entered into the UIAlertView TextField.

  • cancelButtonIndex

This is the read-only index position of the cancel button

  • firstOtherButtonIndex

The index of the first other button. The other buttons are the additional buttons that are added to an UIAlertView.

  • dismissWithClickedButtonIndex:animated:

This is an event trigger to detect when the UIAlertView is dismissed

Simple UIAlertView


To demonstrate the UIAlertView initWithTitle we will create a Single View Application that will display an UIAlertView when a button is pressed.

  1. Create a Single View Application
  2. Open the storyboard and add a button to the canvas. Name it: “Simple Alert Me!”
  3. Open the Assistant Editor next to the storyboard and control + drag a connection from the UIButton to the open header file.
  4. In the popover, change the Connection Type to: Action
  5. In the Name field add a name for the button: SimpleAlert
  6. Open the implementation file and add the following code to the body of the SimpleAlert method that was automatically added to the implementation file Figure 1

Figure 1 - Code for SimpleAlert
Figure 1 - Code for SimpleAlert
Figure 2 - Simple UIAlertView
Figure 2 - Simple UIAlertView

Click on the run button in the Xcode Toolbar and click on the button when the app gets loaded in the Simulator. You app should behave like the following Figure 2 demonstrates.

UIAlertView with custom buttons


Instead of the default message and button alert popover we have used in the first example, we can opt to only use buttons. To demonstrate to follow these instruction to to reproduce the sample app:

  • Using the same project as in example 1, add another button to the UIView and name it: “Multi-Button Alert”;
  • Also as before, open the Assistant Editor and add an IBAction for the button by performing a control drag from the button to the header file. In the IBAction popover, change the connection Type to Action and name the IBAction “MultiButtons”;
  • Open the Implementation file and create a new UIAlertView object called: multibutton. However this time around just initialize the object using the init keyboard. See line 1 in Figure 03.;Next set the delegate to nil since we won’t need it (Figure 03);
  • Set the title property to : Multi-Button Alert”;
  • This time we will set the UIAlertView style to the default: UIAlertViewDefault;
  • Add three buttons using the addButtonWithTitle method:
  1. First Multi
  2. Second Multi
  3. Third Multi

Finally add the show method to display the UIAlertView using the supplied parameters when the button is pressed.

Figure 3 - Code for MultipleButtons
Figure 3 - Code for MultipleButtons

To act on the button that was clicked you would need to implement the UIAlertViewDelegate and modify the code to which button is pressed. The alertView:clickedButtonAtIndex: returns the index of the button pressed and also dismisses the UIAlertView. Once you have the index of the button pressed. To demonstrate how to implement the button detection functionality, modify the sample app and add the following code:

  • Open the storyboard and add an UILabel to the Scene to display information based on which button is being pressed.
  • To send the information to the label, you will to add an IBOutlet and a delegate. So open the Assistant Editor and control drag a connection to the header. Call it ButtonPressedNameLabel.
  • Switch to the header file and add the UIAlertViewDelegate
  • Once done, open the implementation file and implement the - (void)alertView:clickedButtonAtIndex method to detect which button is pressed.
  • Before adding the code, change the mutlibutton’s delegate from nil to self in the MutliButtons IBAction method: multibutton.delegate = self;. This will tell the UIAlertView that the view controller is its delegate.
  • The easiest way to implement logic to work with the buttons is use the button titles, so add a if/else with the buttonTitleAtIndex to check which button is pressed and add code to the body of the if statement Figure 04. When the button is pressed, this method is called, provided that the delegate is set to self. The buttonPressedName NSString variable retrieves the title of the button pressed at buttonIndex. Then it is a simple operation perform a series if statement to see which one was pressed and implement some logic in the body. Another way to go is to use a switch statement which requires a NSInteger as input to detect the index being pressed. See Figure 05. The outcome is the same.

Figure 4 - Code for clickedButtonAtIndex to detect which button is pressed
Figure 4 - Code for clickedButtonAtIndex to detect which button is pressed
Figure 5 - Same logic as above but using a switch statement instead.
Figure 5 - Same logic as above but using a switch statement instead.

This type of UIAlertView is great for menus and such. If you created the app as mentioned, you should the following output, or near abouts Figure 6. Clicking on the button labelled, “Multiple Buttons Alert” will display the UIAlertView with the three buttons Figure 7. Selecting any one of them will display the corresponding text in the label on the view controller Figure 8.

Figure 6 - Running App
Figure 6 - Running App
Figure 7 - Multi Button UIAlertView
Figure 7 - Multi Button UIAlertView
Figure 8 - Output From Pressed Button
Figure 8 - Output From Pressed Button

UIAlertView as an Input form Popover


The UIAlertView provides properties to display, not only buttons and text, but input fields as well. To abe able to add an input field to an UIAlertview object, you have to change the alertViewStyle property to UIAlertViewStylePlainTextInput. The TextField is provided for free when you select the style. To demonstrate this example, we will again modify the app.

  • Rename the button in the Navigation Bar to: What Is Your Name
  • Control drag to create an IBAction. Change the connection type to Action and naming the IBAction: NamePlease.
  • In the implementation method of NamePlease, create a new UIALertView object, inputAlert.
  • Set the delegate to self, or the view controller as before
  • Add a message value as a prompt: “What Do I Call You!”
  • Also add a title: alertInput.title = @"Give Me A Name";
  • Then change the style of the UIAlertView to UIAlertViewStylePlainTextInput
  • Add a button labelled, “OKAY!” using the addButtonWithTitle method
  • Finally call the show method to actually load the UIAlertView

Figure 9 below has the complete code of the NamePlease method. You can also copy the code from the Code section at the end of this tutorial.

Figure 9 - NamePlease Code
Figure 9 - NamePlease Code

Test the app in the Simulator. The output should resemble Figure 10 below. The keyboard is provided to allow for input and it is automatically dismissed when the UIAlertView is dismissed by pressing the “OKAY!” button. This is handy for prompting the user for some type of input. You could also add an extra button to allow the user to cancel out gracefully.

Figure 10 - TextField Input UIAlertView
Figure 10 - TextField Input UIAlertView

Changing the style to UIAlertViewStyleSecureTextInput changes the input display to dots while allowing you to see the character entered for a second or two before converting the character to a dot. We see this type of input in many system apps from Apple.

To get value of the TextField in the UIAlertView, you would need to add the textFieldAtIndex method to the delegate method which return an instance of the UITextField. See Figure 11 for code listing.

  • Again to demonstrate, change the sample app’s alertView to detect if the OKAY! button was pressed
  • Create an UITextField object by assigning the UITextField at index : buttonIndex from the calling alertView
  • Assign the value of the referenced UITextField in the label.

Figure 11 - Code To Get UITextField Input
Figure 11 - Code To Get UITextField Input

UIAlertview as an Login Form


This last example will demonstrate the UIAlertViewStyleLoginAndPasswordInput style. This style property displays two UITextField pre configured for a user name and password. Using the code technique from above, you would get the UITextField values from the UITextField in UIAlertView and process a login to fit your needs. Code listing for the two methods are in figure 12 & 13.

  • Add a new button the Navigation Bar named: Credentials.
  • Add an IBAction for the button, also called: Credentials.
  • In the Credentials method create a new UIAlertView object: credentialAlert
  • Add a delegate to the view controller: self
  • Change the title property to : Credentials
  • Change the style to UIAlertViewStyleLoginAndPasswordInput
  • Add or change message to something like : Please Provide Your Credentials
  • Add a button, called, Login, to trigger the callback
  • Next comment out the code from the first two examples in the alertView:clickedButtonAtIndex method and add an if clause to check for the Login button
  • As before create an UITextField to get the values of the username and password fields in the UIAlertView
  • Add the value to the label to acknowledge receipt of the credentials

Figure 12 - Get Login UITextField Values
Figure 12 - Get Login UITextField Values
Figure 13 - Credentials Code
Figure 13 - Credentials Code

Figure 14 offers a screenshot of the login implementation of the UIAlertView for logins. The UIAlertView is a very versatile addition to the SDK with IOS 5. It provides a nice cross between a view controller and an action sheet with very little code. Check out the complete code listing below.

Figure 15 - Implementation of Login UIAlertView
Figure 15 - Implementation of Login UIAlertView

klViewController.h

//
//  klViewController.h
//  UIAlertViewApplication
//
//  Created by Kevin Languedoc on 3/22/12.
//  Copyright (c) 2012 Kevin Languedoc. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface klViewController : UIViewController<UIAlertViewDelegate>
- (IBAction)SimpleAlert:(id)sender;
- (IBAction)MultipleButtons:(id)sender;
@property (strong, nonatomic) IBOutlet UINavigationBar *NavBar;
@property (strong, nonatomic) IBOutlet UILabel *ButtonPressedNameLabel;
- (IBAction)NamePlease:(id)sender;
- (IBAction)Credentials:(id)sender;

@end

klViewController.m

//
//  klViewController.m
//  UIAlertViewApplication
//
//  Created by Kevin Languedoc on 3/22/12.
//  Copyright (c) 2012 Kevin Languedoc. All rights reserved.
//

#import "klViewController.h"

@implementation klViewController
@synthesize NavBar;
@synthesize ButtonPressedNameLabel;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    NavBar.topItem.title = @"UIAlertView Examples";

	// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [self setNavBar:nil];
    [self setButtonPressedNameLabel:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
}

- (IBAction)SimpleAlert:(id)sender {
    UIAlertView * simpleAlert = [[UIAlertView alloc] initWithTitle:@"Simple Alert" message:@"This is a simple alert message" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [simpleAlert show];
}

- (IBAction)MultipleButtons:(id)sender {
    UIAlertView * multibutton = [[UIAlertView alloc] init];
    
    multibutton.delegate = self;
    multibutton.title = @"Multi-Button Alert";
    multibutton.alertViewStyle = UIAlertViewStyleDefault;
    [multibutton addButtonWithTitle:@"First Multi"];
    [multibutton addButtonWithTitle:@"Second Multi"];
    [multibutton addButtonWithTitle:@"Third Multi"];
    [multibutton show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    NSString * buttonPressedName = [alertView buttonTitleAtIndex:buttonIndex];
    
    
  /*  Code for example 1   */
   if(buttonPressedName == @"First Multi"){
        self.ButtonPressedNameLabel.text = [buttonPressedName stringByAppendingString:@" was pressed"];
    }else if(buttonPressedName == @"Second Multi"){
        self.ButtonPressedNameLabel.text = [buttonPressedName stringByAppendingString:@" was clicked by Kevin"];

    }else{
        NSString * paddingText = [[NSString alloc]init];
         paddingText = @"I guess the ";                       
        self.ButtonPressedNameLabel.text = [[paddingText stringByAppendingString:buttonPressedName] stringByAppendingString:@" was pressed"];
    }

     /* Code for sample 2
    NSString * buttonPressedName = [alertView buttonTitleAtIndex:buttonIndex];
    NSString * paddingText = [[NSString alloc]init];
    switch (buttonIndex) {
        case 0:
            self.ButtonPressedNameLabel.text = [buttonPressedName stringByAppendingString:@" was pressed"];
            break;
        case 1:
            self.ButtonPressedNameLabel.text = [buttonPressedName stringByAppendingString:@" was clicked by Kevin"];
            break;
        default:
            
            paddingText = @"I guess the ";                       
            self.ButtonPressedNameLabel.text = [[paddingText stringByAppendingString:buttonPressedName] stringByAppendingString:@" was pressed"];
            break;
    }
    */
    
//Code for sample 3
    if(buttonPressedName == @"OKAY!"){
        
        UITextField * promptField = [alertView textFieldAtIndex:buttonIndex];
        self.ButtonPressedNameLabel.text = promptField.text;
        
    }

    
    if(buttonPressedName == @"Login"){
        
        UITextField * username = [alertView textFieldAtIndex:0];
        UITextField * password = [alertView textFieldAtIndex:1];
               
        if (username.text != @"" && password.text != @"") {
            self.ButtonPressedNameLabel.text = @"Credentials received";
        }
    }


}
- (IBAction)NamePlease:(id)sender {
    UIAlertView * alertInput = [[UIAlertView alloc] init];
    
    alertInput.delegate = self;
    alertInput.title = @"Give Me A Name";
    alertInput.alertViewStyle = UIAlertViewStyleSecureTextInput;
    alertInput.message = @"What Do I Call You!";
    
    [alertInput addButtonWithTitle:@"OKAY"];
   
    [alertInput show];
    
}

- (IBAction)Credentials:(id)sender {
    UIAlertView * credentialAlert = [[UIAlertView alloc] init];
    
    credentialAlert.delegate = self;
    credentialAlert.title = @"Credentials";
    credentialAlert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
    credentialAlert.message = @"Please Provide Your Credentials";
    [credentialAlert addButtonWithTitle:@"Login"];
    
    [credentialAlert show];
}
@end

More by this Author


Comments 8 comments

vinner profile image

vinner 4 years ago from India

Me also want to learn some basics about the basics of iphone and android app development. Thank God i reached your hub. Really useful stuff


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Thank you very much. I am glad you find my tutorials useful.


Apar Raj 4 years ago

Really a nice tutorial for newbies like me. Thanks for this and highly appreciated :)


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

Thanks for the feedback. I really appreciate it.

Kevin


Naveen Shan 4 years ago

Hi klanguedoc,

Very nice tutorial,

It help me to create my own custom UIAlertview to input credential it will work on older iOS version and support of orientation

see the link http://knowledgetransferinobjectivec.blogspot.in/2...


klanguedoc profile image

klanguedoc 4 years ago from Canada Author

cool, glad I was able to help. I took at look at your solution -- very nice.


Gomz 3 years ago

Nice post


David 3 years ago

Nice tutorial... you might not want to do stringVariable == @"whatever" though... that won't always work.

Should be: [stringVariable isEqualToString:@"whatever"];

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working