【问题标题】:Objective-C: whose view is not in the window hierarchyObjective-C:其视图不在窗口层次结构中
【发布时间】:2013-07-06 14:10:39
【问题描述】:

我有这样的代码,一旦我按下一个按钮,我的故事板中的视图就会改变:

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 中的函数,所以我不知道如何解决此问题。

有人可以帮忙吗?

【问题讨论】:

标签: ios objective-c xcode


【解决方案1】:

试试这个,

第一种方法

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

}

【讨论】:

    【解决方案2】:

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

    如果不尝试以下破解:

    [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:viewController animated:YES completion:nil];
    

    【讨论】:

      【解决方案3】:

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

      UIWindow* keyWindow= [[UIApplication sharedApplication] keyWindow];
      [keyWindow addSubview: viewController.view];
      [self presentViewController:viewController animated:YES completion:nil];
      

      【讨论】:

      • 您的代码显示了 viewconntroller,但我仍然遇到同样的错误
      • 如果您查看 -presentViewController 的文档,您会发现它应该将控制器的视图添加到层​​次结构中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-01
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多