How to create an Action Sheet and respond to it

This will bring up the UIActionSheet on iPhone devices from the bottom of the screen:

    // trigger a UIActionSheet
    UIActionSheet *myActionSheet;
    myActionSheet = [[UIActionSheet alloc]initWithTitle:@"My Title" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Cancel in Red" otherButtonTitles:@"Open in Safari", nil];
    myActionSheet.actionSheetStyle = UIActionSheetStyleAutomatic;
    [myActionSheet showInView:self.view];

You can add more buttons if you like by comma separating them. If you don’t feel the need for a button (for example the destructive button) simply set it to nil and it won’t be displayed.

In order to respond to it your class must conform to the UIActionSheetDelegate protocol. Here’s how you implement the method and query which button has been pressed:

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        NSLog(@"This was Button 0");
    }
    
    if (buttonIndex == 1) {
        NSLog(@"This was Button 1");
    }
    
    if (buttonIndex == 2) {
        NSLog(@"This was button 2");
    }
}

The buttonIndex counts the buttons from top to bottom of how they are displayed, starting with 0.





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.