In this tutorial we will see how to make a alert box in iphone. This alert box is viewed by user and is usually created during runtime. This alertview is useful for cases in which you have to display a message to the user. Try It Out explores the UIAlertView in more detail. Download the code as indicated.


TRY IT OUT Using Alert View


1 Using Xcode, create a new View-based Application (iPhone) project and name it UsingViews.

2 In the UsingViewsViewController.m fi le, add the following bold code to the viewDidLoad method:

- (void)viewDidLoad {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@”Hello”
message:@”This is an alert view”
delegate:self
cancelButtonTitle:@”OK”
otherButtonTitles:nil];
[alert show];
[alert release];
[super viewDidLoad];
}

3 Press Command-R to test the application on the iPhone 4 Simulator. When the application is loaded, you see the alert view.

 4 In Xcode, modify the otherButtonTitles parameter by setting it with the value shown in bold:
viewDidLoad {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@”Hello”
message:@”This is an alert view”
delegate:self
cancelButtonTitle:@”OK”
otherButtonTitles:@”Option 1”, @”Option 2”, nil];
[alert show];
[alert release];
[super viewDidLoad];

5 In the UsingViewsViewController.h fi le, add the following line that appears in bold:
#import 
@interface UsingViewsViewController : UIViewController
 {
}
@end



6. In the UsingViewsViewController.m file, add the following method:
- (void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex {
NSLog(@”%d”, buttonIndex);
}


7. Press Command-R to test the application in the iPhone 4 Simulator. Notice that there are now two buttons in addition to the OK button.


8. Click any one of the buttons — Option 1, Option 2, or OK.

9. In Xcode, press Command-Shift-R to view the Debugger Console window. Observe the values printed. You can rerun the application a number of times, clicking the different buttons to observe
the values printed. The values printed for each button clicked are as follows:

➤➤ OK button — 0
➤➤ Option 1 — 1
➤➤ Option 2 — 2
Download Code

Categories:

Leave a Reply