Displaying a message box in an iPhone application is something I have to look up almost every time. I decided it was time to create a tutorial on the subject – then maybe I’d actually remember the syntax. This tutorial will be short, but should cover pretty much everything you’d need to know in order to show alerts in an iPhone application.
If you want to display a simple notification, the syntax is actually pretty short.
message:@"My Message"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
That will give you a message box that looks like this:
Unlike a lot of other UI frameworks, the show function does not block until the alert is dismissed – execution will continue immediately. In order to know what button was pressed we’re going to have to specify a delegate object. In the above example, you’ll see the delegate argument is nil. Alternatively, we could provide an object that will act as a receiver for various actions.
message:@"My Message"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:@"Button 1", @"Button 2", @"Button 3", nil];
// otherButtonTitles is a comma delimited list of strings, terminated with a nil.
[alert show];
…
// This function will be called by the UIAlertView.
– (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
// The cancel button ("OK") is always index 0.
// The index of the other buttons is the order they’re defined.
}
The UIAlertViewDelegate has lots of helpful callbacks that can be used to determine how a user is interacting with your message box. The example above is probably one of the most common – determining which button was pressed when the view is dismissed. The cancel button is always index 0. The index of the other buttons will start at 1 and then increment in the order they’re defined (“Button 1” = 1, “Button 2” = 2, etc).
That code gives us something that looks like this:
And I think that finishes up this tutorial. There’s not much to the UIAlertView, and I hope this tutorial at least points you in the direction of all the things it offers. If you’ve got any questions, feel free to drop them below.
Want to learn more about iPhone programming? Check out these great books: