刚开始使用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];

当前回答

这发生在我身上,当我试图呈现到我的navigationController时,它的视图还没有呈现到视图层次结构上。我解决这个问题的方法是听NavigationControllerDelegate的didShow方法。一旦didShow方法被调用,我知道我可以呈现到我的navigationController上。

注意:使用dispatchQueueAsync.await(.now()) {//present}确实有效,但如果视图需要很长时间才能显示到视图层次结构上,那么它就很容易出错。

其他回答

它主要发生在你在一些后台工作后,如Api命中或特别核心数据服务调用警报。 在应用程序主线程中调用警报。

DispatchQueue.main.async {
   // call your alert in this main thread.
   Constants.alert(title: "Network Error!", message: "Please connect to internet and try again.", controller: self)
}

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

可能和我一样,你有一个错误的根viewController

我想在非uiviewcontroller上下文中显示一个ViewController,

所以我不能使用这样的代码:

[self presentViewController:]

我得到一个UIViewController

[[[[UIApplication sharedApplication] delegate] window] rootViewController]

由于某种原因(逻辑错误),rootViewController是其他的东西比预期的(一个正常的UIViewController)。然后我纠正了这个错误,用UINavigationController替换了rootViewController,问题就解决了。

我在Swift 4.2上也有类似的问题,但我的观点没有从视图周期中呈现出来。我发现我有多个segue要同时呈现。所以我使用dispatchAsyncAfter。

func updateView() {

 DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in

// for programmatically presenting view controller 
// present(viewController, animated: true, completion: nil)

//For Story board segue. you will also have to setup prepare segue for this to work. 
 self?.performSegue(withIdentifier: "Identifier", sender: nil)
  }
}

Swift 5 -后台线程

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

所以这个:

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

是这样固定的:

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