Problems with Cancel Button and UIActionSheet
Asked Answered
A

3

12

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?

Allantoid answered 2/3, 2011 at 22:44 Comment(0)
A
31

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.

Allantoid answered 23/3, 2011 at 13:30 Comment(1)
UIActionSheet has got to be the buggiest piece of code in all of iOSYaya
L
16
if (buttonIndex == actionSheet.cancelButtonIndex)
{
    // Handle cancel action
}

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

Lundell answered 2/3, 2011 at 22:47 Comment(3)
Sorry, I don't think I asked my question properly. The problem is that the first button in the list returns a buttonIndex of zero which gets mistaken for the cancelButtonIndex action. Do you know what I am doing wrong? Thanks.Allantoid
Seems like the right way, so that the OS can do all of the special things it wants for the cancel button (different grouping, style, etc).Volvox
This exactly returns the correct cancel index value.Trichiasis
B
1

add this

[mymenu showInView:self.parentViewController.tabBarController.view];

Blighter answered 26/12, 2012 at 8:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.