self.navigationController?.popToRootViewController(animated: true) 不会关闭任何呈现的视图控制器

self.navigationController?.popToRootViewController(animated: true) doesn't dismiss any presented view controllers

我正在使用 Swift 和 Xcode 中的 Storyboard 开发应用程序。 2 个视图控制器在彼此之上呈现,我想通过按一个按钮来关闭它们。我已经在 Whosebug 上搜索了答案,我找到了 self.navigationController?.popToRootViewController(animated: true),但它没有用。您对为什么这行不通有任何想法吗?

解决方案:

在这种情况下有效的方法是使用另一行代码。我不知道有什么不同,但它以某种方式起作用:

self.view.window!.rootViewController?.dismiss(animated: true, completion: nil)

检查你的 NavigationController 是否为 nil ...

if let nav = self.navigationController {
     nav.popToRootViewController(animated: true)
} else {
   print("nav is nil")
}