不同的警告框按钮上执行不同的操作,取决于警告框

3

我的应用中有3个警告视图。

'wonAlert'(胜利警告)、'lostAlert'(失败警告)和'nagAlert'(催促警告)。

我通过实现这些来为它们提供操作。

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

这个曾经是正常工作的,当我只有'wonAlert'和'lostAlert'时,它们有一个dismiss和一个learn more按钮,可以将它们带到维基百科,现在我想让nag提示将它们带到应用商店。

我该如何使上述方法知道点击来自哪个警报视图,或类似的东西?

谢谢,Sam

4个回答

6

看起来您已经将UIAlertViews存储在变量中,所以我会使用它们:

- (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
    }
}

一个视图可能会有多个相同的标签,你可能会轻易地打错标题或者修改标题后忘了更新委托方法。


1

我在这里回答了一个类似的问题: 带有2个按钮的警报

正确的方法是使用警报的标签属性

在创建每个警报时,通过添加设置其标签变量:

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

然后,在clickedButtonAtIndex方法中,您需要为每个警报添加一个“if”块,如下面的代码所示:
if(alert.tag == 1)
{
    if (buttonIndex == 0)
    {
        //do stuff
    }
    else
    {
        //do other stuff
    }
}
if(alert.tag == 2)
///...etc

1
在您的视图控制器头文件中,添加<UIAlertViewDelegate>以便它同意处理UIAlertView委托方法:
@interface MyViewController : UIViewController <UIAlertViewDelegate> { ... }

在您的视图控制器实现中,添加以下委托方法:
- (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
    }
}

_actionSheet.title属性可用于区分警报视图。我的建议是使用NSString常量或NSLocalizedString()(如果您有本地化字符串表)来为您的警报视图命名。


0
我会采用Alex建议的方法,使用AlertView的标签属性来确定使用过哪个AlertView。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接