开发者

Different actions on alert views buttons, depending on the alert view

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
开发者_JAVA百科

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


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.


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.


I answered a similar question here: Alert with 2 buttons

the correct way to do this is using the tag property of alerts

upon creating each alert, set its tag variable by adding:

alertName.tag = #; //ex: alertName.tag = 1 

Then, in the clickedButtonAtIndex method, you will need to add an 'if' block for each alert you have as shown in the folllowing code:

if(alert.tag == 1)
{
    if (buttonIndex == 0)
    {
        //do stuff
    }
    else
    {
        //do other stuff
    }
}
if(alert.tag == 2)
///...etc


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜