如何从代码中调用另一个ViewController?

时间:2013-11-14 10:56:53

标签: ios objective-c

我在这里阅读了很多主题,但不明白。例如,我有两个ViewControllers。 VC1和VC2。如何以编程方式从VC1转到VC2? 我用NSURLConnection加载数据,然后解析它,如果在收到的数据中我看到字符串“type = 1”,我必须运行另一个ViewController,它必须运行它的所有方法(ViewDidLoad等)。我该怎么做?

在VC1中我有:

If ([[_typeArr objectAtIndex:0]] intValue] == 1)
   //Here I must to run VC2

5 个答案:

答案 0 :(得分:1)

首先,您需要在 VC1.m 文件中添加#import VC2.h文件

时写下面的代码
if ([[_typeArr objectAtIndex:0]] intValue] == 1)
{
   VC2 *vc2 = [[VC2 alloc] init]; // create object of VC2
   [self presentViewController:vc2 animated:YES completion:nil]; 
            OR // if you have to use navigation controller then
   [self.navigationController pushViewController:vc2 animated:YES];
}

答案 1 :(得分:0)

以下是将新视图控制器推送到导航控制器堆栈的代码。希望这是你正在寻找的。

UIViewController *viewController = [[[UIViewController alloc] init] autorelease];
[self.navigationController pushViewController:viewController animated:YES];

答案 2 :(得分:0)

这取决于 - 如果您使用故事板构建应用程序,则应使用方法触发一个序列:

performSegueWithIdentifier:

如果你没有使用故事板并且你正在使用UINavigationController,你应该通过:

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

你是不是在使用NavigationController,也许UIModalViewController是你的正确答案。

这真的取决于...但我强烈建议你使用storyboard和segue。非常好,与UINavigationController的连接是自己创建的。

答案 3 :(得分:0)

1. If your Application is using Navigation controller Without Storyboard try this:

if ([[_typeArr objectAtIndex:0]] intValue] == 1)
{
    VC2 *vc2 = [[VC2 alloc] initWithNibName:@"VC2"]; // create object of VC2
    [self.navigationController pushViewController:vc2 animated:YES];
}

2.If your Project is not using neither Navigation controller nor Storyboard try this:
 if ([[_typeArr objectAtIndex:0]] intValue] == 1)
   {
     VC2 *vc2 = [[VC2 alloc] initWithNibName:@"VC2"]; // create object of VC2
     [self presentViewController:vc2 animated:YES completion:nil]; 
}

3.If your Project is using Navigation controller and Storyboard Follow This Step:

      1.In Storyboard File > Go to Your First View Controller on left Side  >> Right Click >> Give   Connection From Manual to Second View Controller (Under Trigger Segue)

As Result Connection is created With Arrow In Circle 

Click On Arrow Button (If you can not see that arrow Zoom out  storyboard file) 

On Right Side Click on Attribute Inspector 

Give Identifier Name "VC2"


Now in Code Part:

if ([[_typeArr objectAtIndex:0]] intValue] == 1)
{
   [self performSegueWithIdentifier:@"VC2" sender:nil]; // Must Be Same as given In Identifier field in storyboard
}

答案 4 :(得分:-1)

只需查看导航控制器的教程,因为您需要一个容器控制器,可以将导航从一个导航到另一个,如果有的话,这里有一些链接可以返回并返回特定问题。

http://www.ralfebert.de/archive/ios/tutorial_iosdev/navigationcontroller/

http://www.techotopia.com/index.php/Creating_a_Navigation_based_iOS_5_iPhone_Application_using_TableViews

http://www.appcoda.com/use-storyboards-to-build-navigation-controller-and-table-view/