tags:

views:

200

answers:

3

I have 3 alert views in my apps. 'wonAlert' 'lostAlert' 'nagAlert'

I implement this to give them actions.

 -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

This used to work fine, when I had just the 'wonAlert' and 'lostAlert', they had a dismiss and a learn more button that took them to wikipedia, now I want the nag alert to take them to the app store.

how can I make it so the above method knows which alert view the tap is coming from, or something like that?

Cheers, Sam

A: 

In your view controller header file, add <UIAlertViewDelegate> so that it agrees to handle UIAlertView delegate methods:

@interface MyViewController : UIViewController <UIAlertViewDelegate> { ... }

In the implementation of your view controller, add the following delegate method:

- (void) alertView:(UIAlertView *)_actionSheet clickedButtonAtIndex:(NSInteger)_buttonIndex {
    if ([_actionSheet.title isEqualToString:@"titleOfMyAlertView"]) {
        if (_buttonIndex == 0) {
            // do stuff for first button
        } 
        else if (_buttonIndex == 1) {
            // do something for second button
        }
        // etc. if needed
    }
}

The _actionSheet.title property can be used to distinguish between alert views. My recommendation is to use NSString constants or NSLocalizedString(), if you have a localized strings table, to title your alert views.

Alex Reynolds
A: 

I would do what Alex suggests, but use the tag property of the AlertView to determine which AlertView had been used.

Ben Gottlieb
+4  A: 

It sounds like you've got the UIAlertViews in variables, so I'd use them:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView == wonAlert) {
        //DO STUFF
    }
    else if (alertView == lostAlert) {
        //DO OTHER STUFF
    }
    else if (alertView == nagAlert) {
        //OPEN APP STORE
    }
}

More than one view can have the same tag and you can easily mistype the title or change it and forget to update the delegate method.

David Kanarek