Search code examples
iosobjective-cuialertviewuialertviewdelegate

UIAlertview clicked button at index delegate method not being called


Am new to AlertViews with actions. Have set mine up as in the examples I found here including setting the delegate method in my .h, but when I debug find that it is not reaching my clickedButtonAtIndex method. Probably missing something simple :-/ Any help solving this would be appreciated, thanks. Here's my code:

.h file

@interface LineDetailViewController : UIViewController <UIAlertViewDelegate>

. m file:

- (IBAction)removeLineButton:(UIButton *)sender {

    NSString * requestSubmitText = [NSString stringWithFormat:@"Hey Bro are you sure you want to remove this line you created, it will also remove all the reviews attached and can not be undone?"];

    UIAlertView *removeLineRequest = [[UIAlertView alloc] initWithTitle:@"WARNING!!"
                                                          message:requestSubmitText
                                                         delegate:nil
                                                cancelButtonTitle:@"Remove It"
                                                otherButtonTitles:@"Cancel",nil];
    [removeLineRequest show];

- (void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex{
    //if (buttonIndex == [alertView cancelButtonIndex]){
    if (buttonIndex == 0){
        NSLog(@"Cancel button pressed");
    }else{
        NSLog(@"other button pressed");
    }
}

Solution

  • You have to set delegate to self

    UIAlertView *removeLineRequest = [[UIAlertView alloc] initWithTitle:@"WARNING!!"
                                                              message:requestSubmitText
                                                             delegate:self // <- here
                                                    cancelButtonTitle:@"Remove It"
                                                    otherButtonTitles:@"Cancel",nil];