2011-11-21 78 views
1

我有两个警报按钮,我不能让第二个按钮去到另一个URL,它只是去第一个按钮相同的URL。第二次警报弹出没有问题,第二次警报上的“访问”按钮与第一次警报相同。第二个AlertView openURL不起作用

-(IBAction)creditBtn: (id) sender{ 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Credits" 
               message:@"Message 
               delegate:self 
               cancelButtonTitle:@"Cancel" 
               otherButtonTitles:@"Visit", nil];  

    [alert show];        
    [alert release]; 
}       

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
     if(buttonIndex==1) { 
     [[UIApplication sharedApplication] openURL: 
         [NSURL URLWithString:@"http://website1.com"]]; 
     } 
} 

-(IBAction)sendBtn: (id) sender2{ 
    UIAlertView *alert2 = [[UIAlertView alloc] 
          initWithTitle:@"Send Me Your Feedback" 
          message:@"Message" 
          delegate:self 
          cancelButtonTitle:@"Cancel" 
          otherButtonTitles:@"Visit", nil]; 
    [alert2 show]; 
    [alert2 release]; 
} 

- (void)alertView2:(UIAlertView *)alertView2 clickedButtonAtIndex:(NSInteger)buttonIndex{ 
    // resign the shake FirstResponder, no keyboard if not 
    //[self resignFirstResponder]; 
    // making the otherButtonTitles button in the alert open a URL 
    if(buttonIndex==0){ 
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://website2.com"]]; 
    } 
} 

回答

1

您的问题与alertView2委托方法。委托是一种在发生问题时自动调用的方法。在这种情况下,当UIAlertView关闭时,会自动调用delagate方法:- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex。所以你的问题是你的alert2也在调用与你的第一个警报相同的委托方法。

但有一个非常简单的修复方法。为了修复它,我们为每个alertView添加一个标签。然后在委托方法中,我们检查标签以查看它是哪个警报。这里是如何做到这一点:

//Set up your first alertView like normal: 
-(IBAction)creditBtn: (id) sender{ 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Credits" 
               message:@"Message" 
               delegate:self 
               cancelButtonTitle:@"Cancel" 
               otherButtonTitles:@"Visit", nil]; 
     alert.tag = 0; //Here is that tag 
     [alert show];        
     [alert release]; //Although this is unnecessary if you are using iOS 5 & ARC 
} 

我唯一改变的是我的标记第一次警报作为警报0。这意味着,只要每个警报都有不同的标签,我们可以看出其中的差别。

然后设置你的第二个alertView就像你正在做的:

​​

通知我命名这两个alertViews alert。我没有必要将它们命名为alert & alert2因为这个东西叫做变量作用域。变量范围意味着变量存在一段时间,然后死亡。因此,在你的情况下,因为你在方法内部创建了变量UIAlertView *alert,在该方法结束时,该变量死亡。有关更多的信息来源,看看这个:Article on Variable Scope

于是最后,被关闭响应该alertView委托方法:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
     if(alert.tag == 0 && buttonIndex == 1)  //Show credits 
       [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://website1.com"]]; 

     else if(alert.tag == 1 && buttonIndex == 1)  //Send feedback 
       [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://website2.com"]]; 
} 

这就是所有有它。如果您需要更多帮助,请在评论中告诉我。