iPhone Developer's Toolbox

iPhone 101

Code Tips

Resources

Links

More

iPhone Code Tips: User Interface
UIAlertView

Alert views are pop-up views that appear over the current view on the iPhone.

Creating and showing an alert:

UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Really reset?" message:@"Do you really want to reset this game?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil] autorelease]; // optional - add more buttons: [alert addButtonWithTitle:@"Yes"]; [alert show];

If you add the UIAlertViewDelegate protocol to your controller, you can also add the following method which is called after the user dismisses the alert view:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { if (buttonIndex == 1) { // do stuff } }

Button indices start at 0 (for the cancelButton specified in the alloc/init), and go up by 1 for each addButtonWithTitle call you add. If you have a lot of alerts, your didDismiss method can keep track of which one is being dismissed if you add the setTag call to the alert initialization: [alert setTag:23];

UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Error" message:@"I'm sorry Dave, I'm afraid I can't do that." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease]; [alert setTag:12]; [alert show]; ... later ... - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { if ([alertView tag] == 12) { // it's the Error alert if (buttonIndex == 0) { // and they clicked OK. // do stuff } } }

TopHome