views:

744

answers:

1

UIAlertSheet's constructor takes an otherButtonTitles parameter as a varg list. I'd like to specify the other button titles from an NSArray instead. Is this possible?

i.e. I have to do this:

id alert = [[UIActionSheet alloc] initWithTitle: titleString
                                  delegate: self
                                  cancelButtonTitle: cancelString
                                  destructiveButtonTitle: nil
                                  otherButtonTitles: button1Title, button2Title, nil];

But since I'm generating the list of available buttons at runtime, I really want something like this:

id alert = [[UIActionSheet alloc] initWithTitle: titleString
                                       delegate: self
                              cancelButtonTitle: cancelString
                         destructiveButtonTitle: nil
                              otherButtonTitles: otherButtonTitles];

Right now, I'm thinking that I need to have a seperate call to initWithTitle: for 1 item, 2 items and 3 items. Like this:

if ( [titles count] == 1 ) {
     alert = [[UIActionSheet alloc] initWithTitle: titleString
                                         delegate: self
                                cancelButtonTitle: cancelString
                           destructiveButtonTitle: nil
                                otherButtonTitles: [titles objectAtIndex: 0], nil];
} else if ( [titles count] == 2) {
     alert = [[UIActionSheet alloc] initWithTitle: titleString
                                         delegate: self
                                cancelButtonTitle: cancelString
                           destructiveButtonTitle: nil
                                otherButtonTitles: [titles objectAtIndex: 0], [titles objectAtIndex: 1],  nil];
} else {
    // and so on
}

That's a lot of duplicate code, but it might actually be reasonable since I have at most three buttons. How can I avoid this?

+4  A: 

Instead of adding the buttons when you initialize the UIActionSheet, try adding them with the addButtonWithTitle method using a for loop that goes through your NSArray.

id alert = [[UIActionSheet alloc] initWithTitle: titleString
                              delegate: self
                              cancelButtonTitle: cancelString
                              destructiveButtonTitle: nil
                              otherButtonTitles: nil];

NSEnumerator *e = [titles objectEnumerator];
id title;

while ( (title = [e nextObject]) ) {
    [alert addButtonWithTitle:title];
}
Simon
easier than that: `for (NSString * title in titles) { [alert addButtonWithTitle:title]; }` There's no need to create an enumerator.
Dave DeLong
Aw. I swear I looked for a way to add buttons in the docs. I must have just missed it. Thanks for the save.
Steven Fisher