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

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

问题描述

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

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];

视图控制器的

Identifier 要么等于视图控制器的类名,要么是您可以在故事板的身份检查器中分配的故事板 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.

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

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