2011-11-21 50 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"]]; 
} 

這就是所有有它。如果您需要更多幫助,請在評論中告訴我。