使buttonUIAlertView执行塞格

我为一个动作创build了一个UIAlertView ,给了我两个选项。 我希望用户能够点击一个button,并执行Segue。

这是我迄今为止的代码:

 - (IBAction)switchView:(id)sender { UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Please Note" message:@"Hello this is my message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Option 1", @"Option 2", nil]; [myAlert show]; } - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { NSString *buttonTitle = [alertView buttonTitleAtIndex:buttonIndex]; if ([buttonTitle isEqualToString:@"Option 1"]) { } } 

是的,起初不是很明显,你需要创build一个手动的继续。

在这里输入图像说明

selectViewController将执行推( 我是谁推 ),并手动连接到推视图控制器( 推视图控制器 )。

在这里输入图像说明

iOS 8 +与Swift

select新创build的segue,并给它一个名字(在我的情况下是"segue.push.alert" ,logging的长名称),并在alert中的action中调用perform segue,如:

 let alert = UIAlertController(title: "My Alert", message: "Be Alerted. This will trigger a segue.", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Segue", style: .Default, handler: { [unowned self] (action) -> Void in self.performSegueWithIdentifier("segue.push.alert", sender: self) })) presentViewController(alert) 

[unowned self]应该小心处理,如果视图控制器可以在动作发生的时候释放,那么你最好用[weak self]然后做self?.performSegue...如果可能发生释放。

老答案

现在,从视图控制器,你可以简单地调用performSegueWithIdentifier:sender: ,在你的情况

 // Using enums is entirely optional, it just keeps the code neat. enum AlertButtonIndex : NSInteger { AlertButtonAccept, AlertButtonCancel }; // The callback method for an alertView - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)index { if (index == AlertButtonAccept) { [self performSegueWithIdentifier:@"segue.push.alert" sender:self]; } } 

以这种方式拥有segues(而不是直接编码)的好处是,你仍然可以有一个很好的应用程序stream概述,混合编码的segues和故事板加载的segues有点挫败了目的。

如果你在你的故事板中给你一个标识符,你可以这样做:

 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { NSString *buttonTitle = [alertView buttonTitleAtIndex:buttonIndex]; if ([buttonTitle isEqualToString:@"Option 1"]) { [self performSegueWithIdentifier:@"foo" sender:nil]; } } 

这是加载ViewController的另一种方法。 您可以使用故事板标识符。 请阅读: 什么是StoryBoard ID,我如何使用它?

首先在Identity Inspector中设置Storyboard ID,然后将以下代码添加到警报委托中。

 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { NSString *buttonTitle = [alertView buttonTitleAtIndex:buttonIndex]; if ([buttonTitle isEqualToString:@"Option 1"]) { // This will create a new ViewController and present it. NewViewController *newViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"NewViewControllerID"]; [NewViewController setModalTransitionStyle:UIModalTransitionStyleCrossDissolve]; [self presentViewController:NewViewController animated:YES completion:nil]; } } 

希望这可以帮助! 🙂