Alerts are widely used in many ways. Very often they are shown on first run to say hello. Also to inform you about something necessary, important. They ask you to wait several seconds, display warnings, errors.
In fact they look just great, stunning and they suits almost any game / application interface. End user might think that we did a lot of hard work to display something so polished like this while it actually only few lines of code.
To display an alert (UIAlertView) like on the screenshot above you need to add:
UIAlertView *simpleAlert = [[UIAlertView alloc] initWithTitle:@"Alert's title" message:@"This is an alert's message." delegate:self cancelButtonTitle:@"and the" otherButtonTitles:@"buttons",nil]; [simpleAlert show]; [simpleAlert release];
You can show the alert wherever you like in you application for example in viewDidLoad method or after pressing button. If you alert has more than two buttons they will be displayed in a single column, not row:
As long as you won’t add an UIAlertViewDelegate protocol to your class and implement alertView:clickedButtonAtIndex: method, pressing any button will only dismiss your alert. Protocol is added in header file of your class:
@interface MyView : UIViewController <UIAlertViewDelegate> {
If you have more than one protocol separate them with commas: <oneProtocol, theOtherProtocol>. Now in implementation (.m) file add this method:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if (buttonIndex == 1) { // do something } else if (buttonIndex == 2) { // do something } }
UIAlertView *complexAlert = [[UIAlertView alloc] initWithTitle:@"Complex Alert" message:@"Select an action" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Sure",@"Not sure",nil]; complexAlert.tag = 1; [complexAlert show]; [complexAlert release];
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if ([alertView tag] == 1) { if (buttonIndex == 1) { // do something } else if (buttonIndex == 2) { // do something } } else { // do something } }
autoAlertView = [[UIAlertView alloc] initWithTitle:@"Auto-dismissed Alert" message:@"This alert will be dismissed in 5 seconds." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; userDismissed = NO; [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(dismissAlert) userInfo:nil repeats:NO]; [autoAlertView show];-(void)dismissAlert { if (userDismissed) return; [autoAlertView dismissWithClickedButtonIndex:0 animated:YES]; [autoAlertView release]; }

