Search code examples
xcodeios7xcode5uialertviewuiactionsheet

How do I add an action to an alert view button?


I am trying to set up an alert view so that when the "Ok" button is pressed, an action sheet comes up with two options. I believe i have it in the right format and there are no errors, but when I run it, nothing happens. please help and thank you in advanced.

-(IBAction)sendSG:(id)sender{
    UIAlertView *message = [[UIAlertView alloc]
                            initWithTitle:@"Send Study Guides!"
                            message:@"Please send your study guides to help create a bigger and more efficent network of study guides. You can send them by email, or you can take a picture of your study guide and send it to us."
                            delegate:self //Changed Here
                            cancelButtonTitle:@"Cancel"
                            otherButtonTitles:@"Ok", nil];

    [message show];

}





-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (buttonIndex == 0) {
        UIActionSheet *sendOptions = [[UIActionSheet alloc]

                                      initWithTitle:@"Add study guide"
                                      delegate:self
                                      cancelButtonTitle:@"Cancel"
                                      destructiveButtonTitle:@"Destructive Button"
                                      otherButtonTitles:@"Email", @"Take a picture", nil];

        [sendOptions showInView:self.view];
        }   

    }



    -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
        if (buttonIndex == 0) {
        NSString *emailTitle = @"Study Guides";

        NSArray *toRecipents = [NSArray arrayWithObject:@"blank@gmail.com"];

        MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];

        [mc setSubject:emailTitle];

        [mc setToRecipients:toRecipents];

        [self presentViewController:mc animated:YES completion:NULL];

        }
    }

Solution

    1. set Delegate of your alert view to self. In your code,

      -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex is not being called due to this

    2. Yes, and change your button index too… forgot to tell you that. it should be 1 for both alertView & actionSheet.

    3. Make your viewController ActionSheet Delegate. add "UIActionSheetDelegate" in your viewController.h

      @interface XYZViewController : UIViewController UIActionSheetDelegate (enclose in angular braces)

    Everything Else will work fine.. Let me know if there is any issue