views:

596

answers:

2

Hey guys,

I have a UIActionSheet with an undetermined number of buttons. I'll need to use the delegate method buttonClickedAtIndex: (or something similar) to decide what method to call when the user clicks a button.

The problem is: how do I decide which button is clicked when different buttons will appear at different indexes in different situations?

One solution is to look at the button's title and act on that - but that's ugly, non-localisable and just bad practise.

Any ideas?

+4  A: 

Is this a case where a single controller might show several sheets, but you know which buttons will appear on each sheet? If so, you can use the sheet's tag property to differentiate between them.

- (IBAction)showEditSheet:(id)sender {
    UIActionSheet * sheet = [[UIActionSheet alloc] initWith...];
    sheet.tag = 1;
    [sheet showInView:self.view];
}
- (IBAction)showDeleteSheet:(id)sender {
    UIActionSheet * sheet = [[UIActionSheet alloc] initWith...];
    sheet.tag = 2;
    [sheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet
  clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch(actionSheet.tag) {
        case 1:
            // This is the edit sheet
            switch(buttonIndex) { ... }
            break;

        case 2:
            // This is the delete sheet
            switch(buttonIndex) { ... }
            break;

        default:
            NSAssert(NO, @"Unknown action sheet");
    }
}
Brent Royal-Gordon
iPhone users were given the choice to use the camera or the library. iPod Touch doesn't have a camera. The instead of changing the buttons on the sheet, we decided to just send the ipod user straight to the library without a choice. So only one sheet with static buttons is used. Problem solved.
Jasarien
A: 

PLEASE don't show people how to [alloc] memory... without ever freeing it.

Ugh.

Donna
Memory management is beyond the scope of this question...
Jasarien