views:

652

answers:

2

Hi all

I've got the problem that the UIAlertViewDelegate method - (void)alertViewCancel:(UIAlertView *)alertView is not called when I cancel a AlertView with it's cancel button.

Weird is that the delegate method - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex works perfectly.

Does anyone have an idea?

Thanks in advance
Sean

- (void)alertViewCancel:(UIAlertView *)alertView
{   
    if(![self aBooleanMethod])
    {
        exit(0);
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //some code
}   

I call this when a button is clicked:

- (void)ImagePickDone
{
    UIAlertView *alertDone = [[UIAlertView alloc] 
                          initWithTitle:@"Done" 
                          message:@"Are u sure?"
                          delegate:self 
                          cancelButtonTitle:@"Cancel" 
                          otherButtonTitles: @"Yes", nil];
    [alertDone show];   
    [alertDone release];
}
+2  A: 

The alertViewCancel is used for when the system dismisses your alert view, not when the user presses the "Cancel" button. Quote from apple docs:

Optionally, you can implement the alertViewCancel: method to take the appropriate action when the system cancels your alert view. If the delegate does not implement this method, the default behavior is to simulate the user clicking the cancel button and closing the view.

If you want to capture when the user presses the "Cancel" button you should use the clickedButtonAtIndex method and check that the index corresponds to the index for the cancel button. To obtain this index use:

index = alertDone.cancelButtonIndex;
pheelicks
Thanks a lot pheelicks. I read it before but I didn't get that's not for the purpose that i wanted, because my english is not that well.
Sean
Don't feel bad, I had this exact same misunderstanding yesterday and I'm a native speaker. I sent feedback mentioning the confusing wording. If more of us do that, maybe others won't be tripped up like we were.
willc2
+1  A: 

You can handle the Cancel at the index 0 of this delegate:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0){
      //cancel button clicked. Do something here.
    }
    else{
      //other button indexes clicked
    }
}   
sfa