Ravi Ravi - 2 months ago 11
Objective-C Question

How to write event handlers for buttons in UIAlertView?

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?

Answer

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
    }
}