检查第二个UIAlertView的buttonIndex

时间:2014-03-05 14:54:44

标签: ios objective-c uialertview

我在一个方法中有2个alertView,我想检查第二个alertView的按钮索引。我该怎么做?我想得到else条件的buttonIndex。以下是我要做的代码。

-(IBAction)buttonClick{

    NSString *connect = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.xyz.com"] encoding:NO error:nil];

    if(connect == NULL) {        
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"No Internet Connection" message:@"Please check your internet connection" delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];        
        [alert show];               
    } else {    
        UIAlertView *alert1=[[UIAlertView alloc]initWithTitle:@"Upload to the server?" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"CANCEL",nil];    
        [alert1 show];        
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        My functionality
}   

2 个答案:

答案 0 :(得分:4)

执行此操作的一种方法是将警报视图的实例设置为全局,并在alertview的委托方法中检查这些实例:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //  assuming the myAlert2 is your alert's instance
    if (alertView == myAlert2)
    {
        if (buttonIndex == 0)
        {
            ...
        }
    }
 }

或者您可以为警报添加标签,然后在alertView的委托方法中检查标签,例如:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 2)
    {
        if (buttonIndex == 0)
        { 
            ...
        }
    }
}

答案 1 :(得分:1)

您可以使用标记进行提醒视图

例如:

 UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"hai" delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil];

alert.tag = 1;

[alert show];

然后你可以检查如下

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1)
    {
        if (buttonIndex == 0)
        { 
            ...
        }
    }
}