Search code examples
iosios7uiactionsheet

How to get grouped looking UIActionSheet buttons when dynamically adding them


Normally, when I add buttons to UIActionSheet statically like so:

UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles: @"Yu", @"Gi", @"Oh", nil];

The appearance of the UIActionSheet will appear grouped like so, with the Cancel buttons a separate group:

enter image description here

However, as I would need to add my buttons dynamically depending on user actions, I found out that if I do so like this:

UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles: nil];
    [actionSheet addButtonWithTitle:@"Yu"];
    [actionSheet addButtonWithTitle:@"Gi"];
    [actionSheet addButtonWithTitle:@"Oh"]; //This is just an example, could add more or less

The resulting UIActionSheet looks like this:

enter image description here

How would I be able to add buttons dynamically but still have them appear grouped as one would when adding buttons statically?

Thanks!


Solution

  • You need to set the Cancel button just like the others:

    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles: nil];
    [actionSheet addButtonWithTitle:@"Yu"];
    [actionSheet addButtonWithTitle:@"Gi"];
    [actionSheet addButtonWithTitle:@"Oh"]; //This is just an example, could add more or less
    actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:@"Cancel"];