These are personal notes take from Lecture 16 of Paul Hegarty’s iPhone App Dev course.

Create a button and an outlet to your view controller to trigger the popping up of your action sheet.

Create a property for the action sheet (you pretty much want to do this for any popover as you will need to track whether it has already been created).

@property (weak, nonatomic) UIActionSheet *actionSheet;
@synthesize actionSheet = _actionSheet;

You can make the reference weak (would normally be strong for an outlet) because you only care if it exists or not.

Then in your button target create the action sheet, handling the case where the action sheet might already be created.

#define DO_SOMETHING_ELSE @"Do something else"

- (IBAction)clickActionSheet:(UIBarButtonItem *)sender {
    if (self.actionSheet) {
        // do nothing
    } else {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Action sheet demo" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Do something else" otherButtonTitles:DO_SOMETHING_ELSE, nil];
        [actionSheet showFromBarButtonItem:sender animated:YES];
    }   
}

Implement the UIActionSheet interface:

@interface KitchenSinkViewController()  <UIActionSheetDelegate>

Then react on action sheet button click:

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *choice = [actionSheet buttonTitleAtIndex:buttonIndex];
    if (buttonIndex == [actionSheet destructiveButtonIndex]) {
        // destroy something
        NSLog(@"Destroy");
    } else if ([choice isEqualToString:DO_SOMETHING_ELSE]){
        // do something else
        NSLog(@"Do something else");
    }
}

Voila!

Couple of things to note about UIActionSheet

Special popover considerations: no cancel button
– action sheet in popover does not show cancel button
– doesn’t need because clicking outside popover dismisses it

Special popover considerations: the popovers passthrougViews
– if you showFromBarButtonItem:animated it adds the toolbar to popover’s passthroughViews
– this is annoying because repeated touches on the bar give multiple action sheets!
– something you just have to handle

Special popover considerations: bar button item handling
– have a weak @property in your class that oints to the UIActionSheet
– set it right after you show the action sheet
– Check that @property at the start of your bar button item’s action method.
– if it’s not-nil (since it is weak, it will only be non-nil if it’s still on screen), just dismiss it
– if it is nil, prepare and show your action sheet

Advertisement