以编程方式从一个视图控制器移动到第二个视图控制器

时间:2015-04-06 07:22:59

标签: ios objective-c

  1. 我在Main.storyboard中添加了第二个View Controller。我给了它一个标题lbvc。我的第一个视图控制器名为JPViewController
  2. 在我的第一个视图控制器JPViewController.m文件中,我想在代码中,在特定方法中移动到该视图控制器。
  3. 我现在的代码,但我认为有一些问题,特别是在第二行,我不知道该用什么代替SomethingHere

    非常感谢你们!

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    SomethingHere *viewController = [storyboard instantiateViewControllerWithIdentifier:@"lbvc"];
    [self presentViewController:viewController animated:YES completion:nil];
    

4 个答案:

答案 0 :(得分:1)

SomethingHere替换为UIViewController并将storyboardID作为lbvc放入第二个vc,否则您的应用会崩溃。

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"lbvc"];
[self presentViewController:viewController animated:YES completion:nil];

如果您不确定在SomethingHere使用什么,请始终使用UIViewController,因为UIViewController是所有ViewControllers的父级。

在某些情况下,您希望将某些值传递给第二个vc,那时您需要使用为第二个vc分配的实际类名。

实施例

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
SecondVC *viewController = (SecondVC *)[storyboard instantiateViewControllerWithIdentifier:@"lbvc"];
viewController.strABC = @"abc value";
[self presentViewController:viewController animated:YES completion:nil];

答案 1 :(得分:0)

你必须在这里给出第二个视图控制器的名称,在那里创建第二个视图控制器的实例,并将控件从第一个视图推送到下一行的第二个视图。跳它会帮助你。

答案 2 :(得分:0)

如果您使用segues在视图控制器之间导航,请在视图控制器对象上使用performSegueWithIdentifier:sender:以编程方式调用导航到第二个视图控制器:

答案 3 :(得分:0)

首先回答你的问题,如果你通过它的storyboard id实例化ViewController,那就意味着你确定它将返回什么类型的对象。 instantiateViewController方法始终返回UIViewController类型。因此,您可以将其强制转换为ViewController类型。

SecondVC *secondVC = (SecondVC *)[storyboard instantiateViewControllerWithIdentifier:@"lbvc"];

其次,使用storyboard对象的最佳方法是获取加载ViewController的对象。 Source

//If creating it from AppDelegate Class
UIViewController *viewController = [self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:@"lbvc"];
//If you are creating it in some ViewController
UIViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"lbvc"];

enter image description here

建议使用它的原因是因为如果您尝试使用下面的代码获取对象,它将创建一个新的故事板对象然后返回。 Source

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

enter image description here

相关问题