2012-04-21 185 views
9

我有一個UIAlertView與此代碼,請你率在AppStore應用程序顯示。UIAlertView按鈕操作?

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Rate on the Appstore!" 
               message:@"" 
               delegate:self 
             cancelButtonTitle:@"Later" 
             otherButtonTitles:@"OK", nil]; 
[alert show]; 
[alert release]; 

但我無法弄清楚如何將動作添加到OK按鈕,帶您在AppStore中應用。

回答

25

這個怎麼樣?

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { 
    if (buttonIndex != [alertView cancelButtonIndex]) { 
     NSLog(@"Launching the store"); 
     //replace appname with any specific name you want 
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms://itunes.com/apps/appname"]]; 
    } 
} 
+0

請更改方法名clickedButtonAtIndex ... 。有可能有人可能會複製上面提到的同一個方法名稱,並且該方法永遠不會被調用。 – 2012-06-13 15:19:53

+0

只需要在ViewController.h中,在@interface ViewController:UIViewController之後添加:它看起來像這樣:「@interface ViewController:UIViewController 」 – JomanJi 2013-01-19 09:42:47

+0

那麼我在哪裏調用此方法? 是怎麼回事它自己被調用,因爲我們在頭文件中添加的UIViewController ,或者我們需要做這樣的事情[自alertView ...]地方嗎? – SteBra 2013-11-21 10:41:52

9

你想要的東西,像下面這樣:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { 
    if (buttonIndex == 0) { 
     NSLog(@"Clicked button index 0"); 
     // Add the action here 
    } else { 
     NSLog(@"Clicked button index other than 0"); 
     // Add another action here 
    } 
} 

的NSLog的出現在控制檯當你按下一個按鈕,幫幫忙,只要你想調試/測試任何東西。

然後爲你想要的動作,你會寫這樣的:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"url_to_app_store"]]; 
+0

對於2鍵警報,而不是檢查如果按鈕指數是'0',你想檢查是否被按下或不取消按鈕'如果(buttonIndex!= [alertView cancelButtonIndex])'。 – chown 2012-04-21 01:56:53

+0

我只是增加額外的幫助來檢查未來,如果有任何其他按鈕被按下,那麼他可以很容易地看到並繼續。 – Domness 2012-04-21 02:00:43

+0

請更改方法名clickedButtonAtIndex ....有可能是一個機會,人們可以複製上述相同的方法名稱和該方法將永遠不會被調用.... – 2012-06-13 15:20:14

0

in swift:使用此代碼塊顯示警報消息。

let alert = UIAlertController(title: "Alert", message: "This is an alert message", preferredStyle: UIAlertControllerStyle.Alert) 

let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {(action:UIAlertAction) in print("This is in alert block") 
}) 

alert.addAction(action) 
self.presentViewController(alert, animated: true, completion: nil)