2

我有这段代码可以工作,所以一旦我按下按钮,我的故事板中的视图就会发生变化:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
ViewController *viewController = (ViewController *)[storyboard instantiateViewControllerWithIdentifier:@"view1"];
[self presentViewController:viewController animated:YES completion:nil];

此代码有效,但是当我再次使用它来更改回我的原始视图时,使用:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
ViewController *viewController = (ViewController *)[storyboard instantiateViewControllerWithIdentifier:@"view2"];
[self presentViewController:viewController animated:YES completion:nil];

它不起作用,我收到此错误:

Warning: Attempt to present <UIViewController: 0x863ad30> on <UITabBarController: 0x86309b0> whose view is not in the window hierarchy!

标识已设置,我不是我的功能,viewdidload所以我不知道如何解决这个问题。

有人可以帮忙吗?

4

3 回答 3

19

尝试这个,

第一种方法

-(IBAction)signin:(id)sender
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"viewController"];
    [[[[UIApplication sharedApplication] delegate] window] setRootViewController:vc];

}

第二种方法(返回上一个视图)

- (IBAction)signout:(id)sender
{

    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"parentViewController"];
    [[[[UIApplication sharedApplication] delegate] window] setRootViewController:vc];

}
于 2013-11-10T09:02:45.460 回答
5

如果您在调用之前调用该方法,则可能会发生这种情况makeKeyAndVisible,因此请在此之后移动调用。

如果不尝试以下 hack:

[[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:viewController animated:YES completion:nil];
于 2013-07-06T14:30:13.617 回答
1

错误消息说明了一切:您必须在显示视图控制器之前将视图控制器的视图添加到窗口:

UIWindow* keyWindow= [[UIApplication sharedApplication] keyWindow];
[keyWindow addSubview: viewController.view];
[self presentViewController:viewController animated:YES completion:nil];
于 2013-07-06T14:24:42.547 回答