Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with Cancel Button and UIActionSheet

How do I determine if the cancel button was pressed on a UIActionSheet?

My UIActionSheet is set up like this:

-(IBAction)fileButtonPressed
{
    UIActionSheet *mymenu = [[UIActionSheet alloc] 
                             initWithTitle:@"Select Folder" 
                             delegate:self 
                             cancelButtonTitle:@"Cancel" 
                             destructiveButtonTitle:nil 
                             otherButtonTitles:nil];

    for (i=0; i<3; i++) 
    { 
        [mymenu addButtonWithTitle:@"Button Name"]; 
    }

    [mymenu showInView:self.view];

}

The problem that I have is that I cannot differentiate between the cancel button and the first button selected.

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{  
    NSString *option = [actionSheet buttonTitleAtIndex:buttonIndex];

    //buttonIndex == 0 if the cancel button is pressed or 
    //if the first item is pressed.
}

Is there a better way of setting this up?

like image 820
iphaaw Avatar asked Mar 02 '11 22:03

iphaaw


2 Answers

The trick turns out to be not to use the automatic cancel button but to add it yourself.

The other slight gotcha is to add the cancel button at the end and not at the beginning.

-(IBAction)fileButtonPressed
{
    UIActionSheet *mymenu = [[UIActionSheet alloc] 
                             initWithTitle:@"Select Folder" 
                             delegate:self 
                             cancelButtonTitle:nil 
                             destructiveButtonTitle:nil 
                             otherButtonTitles:nil];
    for (int nb=0; nb<3; nb++) 
    { 
        [mymenu addButtonWithTitle:@"Button Name"]; 
    }

    mymenu.cancelButtonIndex = [mymenu addButtonWithTitle: @"Cancel"];

    [mymenu showInView:self.view];
}

credit to this stackoverflow entry for the answer.

like image 106
iphaaw Avatar answered Sep 20 '22 19:09

iphaaw


if (buttonIndex == actionSheet.cancelButtonIndex)
{
    // Handle cancel action
}

UIActionSheet also has properties like destructiveButtonIndex and firstOtherButtonIndex to compare against.

like image 41
Mark Adams Avatar answered Sep 23 '22 19:09

Mark Adams