Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write event handlers for buttons in UIAlertView?

Tags:

Say I have a alert view like follows in obj c

UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"title" message:@"szMsg" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:@"download"];         [alert show];         [alert release]; 

Now we have 2 buttons on the alert view (Ok & Download), how to write an event handler for the Download one?

like image 347
Ravi Avatar asked Sep 13 '11 05:09

Ravi


People also ask

What is the difference between UIAlertView and UIAlertController?

The only difference is the alert controller's preferredStyle property, which needs to be set to UIAlertControllerStyle. ActionSheet , or . ActionSheet for short, for action sheets.

What is a UIAlertController?

An object that displays an alert message to the user.

How do I show a popup message in Swift?

Adding Action Buttons to Alert Dialog To create an action button that the user can tap on, we will need to create a new instance of an UIAlertAction class and add it to our alert object. To add one more button to UIAlertController simply create a new UIAlertAction object and add it to the alert.


2 Answers

First you will need to add the UIAlertViewDelegate to your header file like below:

Header file (.h)

@interface YourViewController : UIViewController<UIAlertViewDelegate>  

Implementation File (.m)

UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"title" message:@"szMsg" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:@"download"];         [alert show];         [alert release];  - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {     if (buttonIndex == 0)     {         //Code for OK button     }     if (buttonIndex == 1)     {         //Code for download button     } } 
like image 137
Chetan Bhalara Avatar answered Nov 11 '22 16:11

Chetan Bhalara


Now that most iOS devices have firmare versions with blocks support it’s an anachronism to use the clumsy callback API to handle button presses. Blocks are the way to go, see for example the Lambda Alert classes on GitHub:

CCAlertView *alert = [[CCAlertView alloc]     initWithTitle:@"Test Alert"     message:@"See if the thing works."]; [alert addButtonWithTitle:@"Foo" block:^{ NSLog(@"Foo"); }]; [alert addButtonWithTitle:@"Bar" block:^{ NSLog(@"Bar"); }]; [alert addButtonWithTitle:@"Cancel" block:NULL]; [alert show]; 
like image 43
zoul Avatar answered Nov 11 '22 14:11

zoul