如何以编程方式调用View Controller? [英] How to call a View Controller programmatically?

查看:123
本文介绍了如何以编程方式调用View Controller?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经查看了我可以在这个上找到的所有教程,但我仍然没有答案。我需要从代码中调用另一个视图。我正在使用 UIStoryboards 。我已经通过从 UIButtons 进行控制拖动多次更改了视图,但现在它必须来自代码。如果是用户第一次打开应用程序,我试图从主菜单调用信息页面。但是,我似乎找不到从代码中更改视图的方法。我的所有视图都由相同的文件控制( ViewController2 )。我的主菜单的标识符 ViewControllerMain ,信息页面的标识符是的 ViewControllerInfo 即可。首先我尝试了这个:

I have looked at all the tutorials I can find on this one, and I still don't have the answer. I need to call another view from the code. I am using UIStoryboards. I have changed the view many times by control-dragging from UIButtons, but now it must be from the code. I am trying to call the info page from the main menu if it is the first time the user has opened the app. I cannot seem to find a way to change the views from the code, however. All my views are controlled by the same files (ViewController2). The identifier of my main menu is ViewControllerMain, and the identifier of the info page is ViewControllerInfo. First I tried this:

[ViewControllerMain presentViewController: ViewControllerInfo 
                                 animated:YES 
                               completion: NULL];

然后我尝试为每个人制作不同的 UIViewControllers 并说:

Then I tried making different UIViewControllers for each and saying:

[ViewController2 presentViewController: ViewController 
                              animated:YES 
                            completion: NULL];

两者均无效。对于第一个,它说:

Neither worked. For the first one, it says:


使用未声明的标识符ViewControllerMain。

Use of undeclared identifier ViewControllerMain.

在第二个中,它说:


意外接口名称'ViewController':预期标识符。

unexpected interface name 'ViewController': expected identifier.

我该怎么办?

推荐答案

要创建视图控制器:

UIViewController * vc = [[UIViewController alloc] init];

调用视图控制器(必须从另一个视图控制器中调用):

To call a view controller (must be called from within another viewcontroller):

[self presentViewController:vc animated:YES completion:nil];

一,使用nil而不是null。

For one, use nil rather than null.

从故事板加载视图控制器:

Loading a view controller from the storyboard:

NSString * storyboardName = @"MainStoryboard"; 
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"IDENTIFIER_OF_YOUR_VIEWCONTROLLER"];
[self presentViewController:vc animated:YES completion:nil];

标识符到视图控制器的类名,或者可以在故事板的标识检查器中指定的故事板ID。

Identifier of your view controller is either equal to the class name of your view controller, or a Storyboard ID that you can assign in the identity inspector of your storyboard.

这篇关于如何以编程方式调用View Controller?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆