Detecting button pressed when there are multiple alert views

Jack Humphries picture Jack Humphries · Aug 19, 2011 · Viewed 12.9k times · Source

I have multiple alert views in one view, and I use this code to detect which button was pressed:

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

    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];  

    if ([title isEqualToString:@"OK"]) {

          //for one alert view
          [passCode becomeFirstResponder];

     } else if ([title isEqualToString:@" OK "]) {

        //for another alert view, had to change "OK" to " OK "
        [passCodeConfirm becomeFirstResponder];

    }
}   

Now since there are multiple alert views in one view that do different things, I have to trick the user into thinking "OK" and " OK " are the same thing. It works and looks fine, but it feels kind of messy. Surely there is another way to do this, such as making this specific to an alert view, and then making it specific to another. Do you know how I would do this? Thanks!

Answer

alloc_iNit picture alloc_iNit · Aug 19, 2011

It would be more technical as well better that set unique tag for separate UIAlertView and identify it and access in its delegate method.

For example,

    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Message" message:@"Are You Sure you want to Update?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok",nil];
    [alert setTag:1];
    [alert show];
    [alert release];

    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex  
    {
        if(alertView.tag == 1)
        {
            // set your logic
        }
    }