Browsing articles tagged with " UIAlertView"

How to Show an Alert with UIAlertView

Dec 2, 2009   //   by Derek van Vliet   //   Development  //  6 Comments

2

Showing an alert message to the user isn’t just a handy interface lick, it’s also an invaluable debugging tool. Thankfully, this functionality is built into the iPhone SDK.

To pop an alert with a title, message and OK button, we use the UIAlertView class like so:

UIAlertView *alert = [[UIAlertView alloc]
			initWithTitle: @"Announcement"
			message: @"It turns out that you are playing Addicus!"
			delegate: nil
			cancelButtonTitle:@"OK"
			otherButtonTitles:nil];
[alert show];
[alert release];

But what if you want to have more than one button on the alert and collect user input from it? Well that is pretty simple too. To do that, you first need to create a class that employs the UIAlertViewDelegate delegate like so:

@interface MyClass : NSObject <UIAlertViewDelegate>

Then, in your class, you need to override the alertView method in order to receive input like so:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 0) {
		NSLog(@"user pressed OK");
	}
	else {
		NSLog(@"user pressed Cancel");
	}
}

Finally, we create the UIAlertView and pass in the delegate. Also note that we’ve labeled the Cancel button “Cancel” and added the “OK” button to the other button titles, which differs slightly from the above example.

UIAlertView *alert = [[UIAlertView alloc]
			initWithTitle: @"Announcement"
			message: @"It turns out that you are playing Addicus!"
			delegate: MY_DELEGATE
			cancelButtonTitle:@"Cancel"
			otherButtonTitles:@"OK",nil];
[alert show];
[alert release];

Our Games

Latest Tweets