2.1. Displaying Alerts with UIAlertView

Problem

You want to display a message to your users in the form of an alert. This could be used to ask them to confirm an action, ask for their username and password, or simply let them enter some simple text that you can use in your app.

Solution

Utilize UIAlertView.

Discussion

If you are an iOS user, you have most certainly already seen an alert view. Figure 2-1 depicts an example.

An alert view telling the user that she needs an active Internet connection

Figure 2-1. An alert view telling the user that she needs an active Internet connection

The best way to initialize an alert view is, of course, by using its designated initializer:

UIAlertView *alertView = [[UIAlertView alloc]
                          initWithTitle:@"Title"
                          message:@"Message"
                          delegate:nil
                          cancelButtonTitle:@"Cancel"
                          otherButtonTitles:@"Ok", nil];
[alertView show];

When this alert view is displayed to the user, she will see something similar to that shown in Figure 2-2:

A simple alert view displayed to the user

Figure 2-2. A simple alert view displayed to the user

In order to display an alert view to the user, we use the alert view’s show method. Let’s have a look at the description for each of the parameters that we passed to the initializer of the alert view:

title

The string that the alert view will display on the top when it is shown to the user. This string is Title in Figure 2-2.

message

The actual message that gets displayed ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.