Alerts and Actions
Often in your applications you’ll want to present a message to your users. Perhaps you want to alert them about an error or present them with options for a given action. As an iPhone developer, you handle these situations using alert views and action sheets.
To display an alert message, use the UIAlert View class. You define a title, message, and delegate, and then you configure buttons to be shown in the view.
To display an alert view:
- First, create a simple alert view :
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"title" message:@"message" delegate:nil cancelButtonTitle:@"OK", otherButtonTitles:nil] [myAlert show];
- Using the otherButtonTitles property, you can create the same alert view with up to four additional buttons :
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"title" message:@"message" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:@"button1", @"button2", @"button3", @"button4",nil];
If you have only two buttons in your alert view, they will be displayed side by side. Otherwise, buttons are added from top to bottom, with the cancel button always being at the very bottom. If you don’t need the message or title text, there is room for five buttons in addition to the cancel button.
- You can add buttons after creating your alert view by using the addButtonWith Title: method:
[myAlert addButtonWithTitle: @"new button"];
- To determine which button is tapped, set the delegate, and implement the alertView:clickedButtonAtIndex: delegate method (Code Listing 4.17).
The buttonIndex parameter tells you which button was tapped, starting with the cancel button at index 0. Alert views close automatically when a button is tapped.
Code Listing 4.17 Display an alert view.
Confirming an action
When presenting the user with a number of options, you can use a UIActionSheet.
To create an action sheet:
- An action sheet is created in a similar way to an alert view :
UIActionSheet *mySheet = [[UIActionSheet alloc] initWithTitle:@"Do you really want to delete?" delegate:nil cancelButtonTitle:@"No" destructiveButtonTitle:@"Yes" otherButtonTitles:nil]; [mySheet showInView:self.view];
- Define titles for three types of button.
The cancel button is generally used to dismiss the action sheet.
The destructive button acts as the confirmation of the action and is usually shown in red to indicate its importance.
The other buttons are similar to the alert view and allow you to add more buttons.
Setting any of these parameters to nil prevents the button type from showing.
- Set the delegate, and implement the actionSheet:clickedButtonAtIndex: method, which is called when a button is tapped.
You can compare the buttonIndex parameter to the action sheet’s cancelButtonIndex and destructiveButtonIndex properties to determine which button was tapped.
Code Listing 4.18 shows the code updated with some of these options.
Code Listing 4.18 Adding more options to the action sheet.