UIAlertView Tutorial on Xcode4
The UIAlertView's are very useful and also very simple to use.
In the following you will find a comlpete tutorial on how to use them.
First of all, we need to create a new project; let's call it alertviewtutorial.
-
Hit Command-Shift-N to create a new project on the Xcode4
-
Select the “View-based Application” item then click the “Next” button
-
Set the Product Name field then click on the “Next” button.
-
On the next window click “create” to store your project.
-
On the Project Navigator bar select the alertviewtutorialViewController.h file and edit it to obtain the following code:
#import <UIKit/UIKit.h>
@interface alertviewtutorialViewController : UIViewController <UIAlertViewDelegate> {
IBOutlet UIButton *showAlertButton;
}
@property (assign, nonatomic) IBOutlet UIButton *showAlertButton;
- (IBAction)showAlertView:(id)sender;
@end
-
First we add the UIAlertViewDelegate, this provides the capability to trap the events on the buttons in the UIAlertView.
-
Then we add a button and an action which will show the UIAlertView; when we will push the button, the alert will be shown .
On the Project Navigator bar select the alertviewtutorialViewController.c file and, after
@implementation alertviewtutorialViewController
-
Add the following code:
@synthesize showAlertButton;
- (IBAction)showAlertView:(id)sender
{
UIAlertView *theAlert =[[UIAlertView alloc] initWithTitle:@"The Alert View" message:@"Some infos" delegate:self
cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
[theAlert addButtonWithTitle:@"First option"];
[theAlert addButtonWithTitle:@"Second option"];
[theAlert show];
[theAlert release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
switch (buttonIndex) {
case 0:
printf("Cancel button pressedn");
break;
case 1:
printf("First button pressedn");
break;
case 2:
printf("Second button pressedn");
break;
default:
break;
}
}
-
On the Project Navigator bar select “alertviewtutorialViewController.xib”

-
Add a “Round Rect Button” the the .xib file let's give it “Show Alert View” label.
-
Now connect the button with the showAlertView action
-
hit command-R to run the program
It should work fine.




