以编程方式打开ViewController

时间:2015-05-15 11:44:12

标签: ios objective-c

我在同一个故事板中有另一个ViewController,我想通过点击按钮切换到该故事板。问题是当我尝试控制 - 拖动第二个视图控制器在主视图控制器的ViewController.m文件中创建一个Outlet时,不会创建一个插座。

在Android中,我们可以从另一个活动中打开一个具有不同UI的新活动。我相信在iOS中同样可以实现,所以我的问题是如何创建第二个视图控制器的插座并以编程方式打开

4 个答案:

答案 0 :(得分:2)

在iOS中无法从一个IBOutlet到另一个ViewController创建ViewController,但您可以使用UIStoryboardSegue来实现此目的。

我建议您关注Apple文档中的Tutorial: Storyboards。它将帮助您了解ViewControllers的实际连接方式。

答案 1 :(得分:1)

使用SecondViewController可以通过编程方式打开Storyboard Identifier,您需要为要切换到的班级提供故事板标识名称,请参阅此图片enter image description here,在我的演示中我有使用secondViewController

现在在buttonClick事件方法中使用此代码。

- (IBAction)buttonClicked:(id)sender {
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];

    SecondViewController *secondViewController =  (SecondViewController *)[mainStoryboard instantiateViewControllerWithIdentifier:@"secondViewController"];

    // Use this to show your UIViewController in modal transition.
    [self presentViewController:secondViewController animated:YES completion:nil];

    // Use this to show your UIViewController in push transition with navigation controller
    //[self.navigationController pushViewController:secondViewController animated:YES];

}

答案 2 :(得分:0)

Try this

Viewcontroller*homeVC;
        [self.navigationController setNavigationBarHidden:YES];
        UIStoryboard *storyBoard;

        storyBoard=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        homeVC=(HomeVC*)[storyBoard instantiateViewControllerWithIdentifier:@"HomeVC"];


        [self.navigationController pushViewController:homeVC animated:YES];

答案 3 :(得分:0)

正如其他人所说,你不能这样做。 要覆盖并启动VC并保留其属性,您可以:

首先,在viewControllers之间创建segue:通过双击界面构建器的背景缩小视图。按Ctrl +从一个VC拖动到另一个VC并选择segue类型(例如show)。

为按钮创建操作,您可以在其中:

[self performSegueWithIdentifier:@"myIdentifier" sender:self];

之后,在-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender检查segue的标识符中,设置new yourCustomClassViewController并瞧!

  if ([segue.identifier isEqualToString:@"myIdentifier"]) {
        myCustomClassViewController *myCustomVC = [segue destinationViewController];
        myCustomVC.oldProfile = newProfile;
}
相关问题