以上是我的 Storyboard。第一个 View 连接到 ViewController,第二个没有连接到任何东西。如果我在第一个 View Controller 上有一个按钮,我知道如何显示第二个 View Controller 。我可以单击并从按钮拖动到第二个 View ,创建一个 segue。但是,这一次,我必须在 ViewController.m 中以编程方式显示第二个 View Controller 。例如,在调用某个函数 myFunc 时,我想显示第二个 View Controller 。有人可以解释我该怎么做吗?
我想我需要知道以下几点:
谢谢!
更新:
//setSelectedDate is myFunc. It lives inside myView.m, which is a subview of UIView
- (void)setSelectedDate:(NSDate *)newSelectedDate; {
NSLog(@"override worked");
[super setSelectedDate:newSelectedDate];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
UIViewController *firstController = [storyboard instantiateViewControllerWithIdentifier:@"InitialViewController"];
UIViewController *myController = [storyboard instantiateViewControllerWithIdentifier:@"MySecondViewController"];
[firstController presentViewController:myController animated:YES completion:nil];
}
如果我执行上述操作,我会收到以下警告:
警告:尝试呈现不在窗口层次结构中的 View !
并从此 post我相信这是因为我在错误的地方做这件事。我该如何解决这个问题?
**更新 2:我做了以下事情:**
- (void)setSelectedDate:(NSDate *)newSelectedDate; {
[super setSelectedDate:newSelectedDate];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
UIViewController *firstController = [storyboard instantiateViewControllerWithIdentifier:@"InitialViewController"];
[firstController performSegueWithIdentifier:@"GoToSecondViewController" sender:firstController];
警告消失了,但 View Controller 仍未显示。是因为我在 View 而不是 ViewController 中调用它吗?
最佳答案
您可以执行以下操作之一:
通过从 firstViewController 拖动到第二个,在 Storyboard 中创建一个 segue。然后给那个 segue 一个名字(在 Interface Builder 右 Pane 的 Attributes inspector 下填写 Identifier 字段)。让我们说“GoToSecondViewController”。
在您的 myFunc
方法(或函数),调用
[self performSegueWithIdentifier:@"GoToSecondViewController" sender:nil];
或者
给你的第二个 View Controller 一个 Storyboard ID。在界面生成器中,单击您的第二个 View Controller 。在“身份检查器”下的右侧 Pane 中,填写 Storyboard ID 字段。让我们说“MySecondViewController”。
在您的
myFunc
方法(或函数)执行以下操作:UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:[NSBundle mainBundle]]; // or whatever your storyboard is called
UIViewController *myController = [storyboard instantiateViewControllerWithIdentifier:@"MySecondViewController"];
[self presentViewController:myController animated:YES completion:nil]; // present it or push it if you have a navigation controller
关于ios - 如何以编程方式显示 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26578837/