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?
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.
An object that displays an alert message to the user.
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.
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 } }
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With