如何以编程方式指定segue(不执行segue)?

时间:2013-06-01 08:43:13

标签: cocoa-touch segue

 AView.m
       UIButton *btn = [[UIButton alloc]initWithFrame()];
       [btn addTarget:self action:@selectior(perpareForSegue:sender:) forControlEvents:UIControlEventTouchUpInside];
       [self.view addSubview:btn];


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
       //I want to get destinationViewController of segue with identifier"toNextView" 
       // and then perform the segue
       // Difficulties that I encounter is that I have a NSInvalidArgumentException
       // Is that mean the view controller doesn't know the existence of the segue?
       // I have connected two controller with a segue
}

我想获取带有标识符“toNextView”的segue的destinationViewController 然后执行segue 我遇到的困难是我有一个NSInvalidArgumentException 这是否意味着视图控制器不知道segue的存在? 我用segue连接了两个控制器 谢谢

1 个答案:

答案 0 :(得分:0)

查看class reference of UIStoryboardSegue

方法 prepareForSegue:sender:在触发segue时由storyboard运行时调用。它并不意味着被要求执行segue。

以下是课程参考的解释:

  

当触发segue时,但在视觉转换发生之前,   故事板运行时调用当前视图控制器   prepareForSegue:sender:方法,以便它可以传递任何所需的数据   即将显示的视图控制器。

从课程参考:

  

您仍然可以使用以编程方式启动segue   performSegueWithIdentifier:sender:UIViewController的方法,如果你   想。您可以这样做以从添加的源启动segue   以编程方式,因此在Interface Builder中不可用。

因此,只需指定按钮的选择器,然后在选择器内部调用 performSegueWithIdentifier:sender:方法。

[btn addTarget:self action:@selector(whateverAction) forControlEvents:UIControlEventTouchUpInside];

- (void)whateverAction {
    [self performSegueWithIdentifier:@"toNextView" sender:nil];
}

如果你想将一个对象传递给segue的目标视图控制器,那么<​​em>其中prepareForSegue:sender:方法将在类引用中解释,例如:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"toNextView"]) {
        DestinationViewController *vc = (DestinationViewController *)[segue destinationViewController];
        //do whatever you want to do with vc, including passing of data, setting property, etc.
    }
}