How to Alert the User in iOS Apps - dummies

By Rajiv Ramnath

Alert views interrupt users while they’re using an iOS app, requiring them to stop what they’re doing and either dismiss the alert or select an action. Note that an Alert view appears on top of the content on an app’s screen — after all, the alert’s purpose is to catch the user’s attention.

The figure shows an Alert view from a Tic-Tac-Toe app. Clicking Yes clears the old game and starts a new one. Clicking No ends the game.


As with most iOS views, you use delegation to implement an alert. However, the specification of the delegate is done programmatically — that is, not through the interface builder, as for buttons. The following code illustrates how to do so (taken from the GameView class; implemented in TTTGameView.m and .h):

 - (void) promptToProceed :(TTTGameSessionViewController *) GameViewController {
  UIAlertView *alert = [[UIAlertView alloc] init];
  [alert setTitle:@"Game Over!"];
  [alert setMessage:@"Play Another Game?"];
  [alert addButtonWithTitle:@"Yes"];
  [alert addButtonWithTitle:@"No"];
  [alert setDelegate:GameViewController];
  [alert show];

After alert is instantiated in the typical Objective-C manner (using alloc followed by init), the title and message properties are set, and the Yes and No buttons are added as subviews to the Alert view using the method addButtonWithTitle. Just before the alert is shown (using the show method), the Game Session view controller is set as the delegate to the alert using the setDelegate method.

Because the Game Session view controller is set as the delegate to the alert, an action in the Game Session view controller class is triggered when a button of the alert is touched.

Any delegate to the alert must implement the UIAlertViewDelegate protocol, and therefore, a method named clickedButtonAtIndex as the delegate action method for the alert. Check TTTGameSessionViewController.m, and you’ll see this clickedButtonAtIndex method, which is also shown in the following code:

 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
  if (buttonIndex == 0){
   [self playNewGame];
  } else if (buttonIndex == 1) {

The Yes button was added first, so its index is 0. As you can see, touching this button starts a new game. The No button was added second, so its index is 1. Touching it does nothing.