刚开始使用Xcode 4.5,我在控制台得到了这个错误:

警告:试图在< ViewController: 0x1ec3e000>上显示< finishViewController: 0x1e56e0a0 >,其视图不在窗口层次结构中!

视图仍在显示,应用程序中的一切都在正常工作。这是iOS 6的新功能吗?

这是我用来在视图之间更改的代码:

UIStoryboard *storyboard = self.storyboard;
finishViewController *finished = 
[storyboard instantiateViewControllerWithIdentifier:@"finishViewController"];

[self presentViewController:finished animated:NO completion:NULL];

当前回答

我修复了这个错误,将最顶部的视图控制器存储为常量,这是在rootViewController的while循环中发现的:

if var topController = UIApplication.shared.keyWindow?.rootViewController {
    while let presentedViewController = topController.presentedViewController {
        topController = presentedViewController
    }
    topController.present(controller, animated: false, completion: nil)
    // topController should now be your topmost view controller
}

其他回答

In case it helps anyone, my issue was extremely silly. Totally my fault of course. A notification was triggering a method that was calling the modal. But I wasn't removing the notification correctly, so at some point, I would have more than one notification, so the modal would get called multiple times. Of course, after you call the modal once, the viewcontroller that calls it it's not longer in the view hierarchy, that's why we see this issue. My situation caused a bunch of other issue too, as you would expect.

总之,无论你做什么,都要确保模态不会被调用超过一次。

我的问题是,在我调用窗口上的makeKeyAndVisible()之前,我在UIApplicationDelegate的didFinishLaunchingWithOptions方法中执行segue。

Swift 5 -后台线程

如果一个警报控制器在后台线程上执行,那么“Attempt to present…”“其视图不在窗口层次结构中”的错误可能会发生。

所以这个:

present(alert, animated: true, completion: nil)
    

是这样固定的:

DispatchQueue.main.async { [weak self] in
    self?.present(alert, animated: true, completion: nil)
}

我也有这个问题,但这和时间无关。我使用一个单例来处理场景,并将其设置为presenter。换句话说,“自我”没有连接到任何东西。我只是把它的内部“场景”变成了新的主持人,瞧,它成功了。(瞧,当你知道它的意思后,它就失去了它的触感,嘿)。

所以,这不是关于“神奇地找到正确的方法”,而是关于理解你的代码所处的位置以及它在做什么。我很高兴苹果给出了如此直白的警告信息,甚至还带有感情色彩。向苹果开发者致敬!!

我通过将start()函数移动到解散完成块内部来修复它:

self.tabBarController.dismiss(animated: false) {
  self.start()
}

Start包含对self.present()的两个调用,一个用于UINavigationController,另一个用于UIImagePickerController。

这为我解决了问题。