2012-04-21 121 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)