Wednesday, May 29, 2013

UIActionSheet cancelButtonIndex example in Objective C (iOS).

UIActionSheet cancelButtonIndex

The index number of the cancel button.

@property(nonatomic) NSInteger cancelButtonIndex

Discussion of [UIActionSheet cancelButtonIndex]
Button indices start at 0. The default value of this property is normally -1, which indicates that no cancel button has been set. However, a cancel button may be created and set automatically by the initWithTitle:delegate:cancelButtonTitle:destructiveButtonTitle:otherButtonTitles: method. If you use that method to create a cancel button, you should not change the value of this property.[UIActionSheet cancelButtonIndex]

When presenting an action sheet on an iPad, there are times when you should not include a cancel button. For more information on when you should include a cancel button, see the class overview or iOS Human Interface Guidelines.

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

    for (i=0; i<3 data-blogger-escaped-br="" data-blogger-escaped-i="" data-blogger-escaped-nbsp="">     {
        [mymenu addButtonWithTitle:@"Button Name"];
    }

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

}

Example of [UIActionSheet cancelButtonIndex].
   for(int index = 0; index < buttonTotal; index++)
   {
    [actionSheet addButtonWithTitle:[NSString stringWithFormat:buttonText, [buttonItems objectAtIndex: index]]];
   }

   [actionSheet addButtonWithTitle:@"Cancel"];
   actionSheet.cancelButtonIndex = actionSheet.numberOfButtons;

UIActionSheet cancelButtonIndex example.
NSArray *array = [[NSArray alloc] initWithObjects:
                      [NSString stringWithString:@"1st Button"],
                      [NSString stringWithString:@"2nd Button"],
                      [NSString stringWithString:@"3rd Button"],
                      [NSString stringWithString:@"4th Button"],
                      nil];

    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Title Here"
                                                             delegate:self
                                                    cancelButtonTitle:nil
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:nil];

    for (int i = 0; i < [array count]--; i++) {

        [actionSheet addButtonWithTitle:[array objectAtIndex:i]];

    }

    [actionSheet addButtonWithTitle:@"Cancel"];
    actionSheet.cancelButtonIndex = array.count;

    [actionSheet showInView:self.view];

End of UIActionSheet cancelButtonIndex example article.