我对Swift比较陌生
尝试使用窥视和弹出PreviewActionItems“ edit”在编辑模式下打开SpeciesDetailViewController。尝试获取提示以显示SpeciesDetailViewController时出现问题,并收到错误消息"Warning: Attempt to present SpeciesDetailViewController whose view is not in the window hierarchy"
。我在found here上实现了Jacob Davis的解决方案。
这解决了窗口层次结构错误,但是,在调用SpeciesDetailViewController控制器时,导航控制器和tabBarController均未显示。
虽然我认为这是由SpeciesDetailViewController称为top viewController引起的,但我对如何解决此问题感到困惑。
您能帮我同时显示导航控制器和tabBarController吗?
以下是我当前的代码:
主视图控制器
func showDetailsViewController() {
let topVC = topMostController()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "SpeciesDetailViewController") as! SpeciesDetailViewController
topVC.present(vc, animated: true, completion: nil)
}
func topMostController() -> UIViewController {
var topController: UIViewController = UIApplication.shared.keyWindow!.rootViewController!
while (topController.presentedViewController != nil) {
topController = topController.presentedViewController!
}
return topController
}
最佳答案
对于UITabBarController
和UINavigationController
,您需要不同的实现。
这是我用来获取topMostViewController的代码:
protocol TopUIViewController {
func topUIViewController() -> UIViewController?
}
extension UIWindow : TopUIViewController {
func topUIViewController() -> UIViewController? {
if let rootViewController = self.rootViewController {
return self.recursiveTopUIViewController(from: rootViewController)
}
return nil
}
private func recursiveTopUIViewController(from: UIViewController?) -> UIViewController? {
if let topVC = from?.topUIViewController() { return recursiveTopUIViewController(from: topVC) ?? from }
return from
}
}
extension UIViewController : TopUIViewController {
@objc open func topUIViewController() -> UIViewController? {
return self.presentedViewController
}
}
extension UINavigationController {
override open func topUIViewController() -> UIViewController? {
return self.visibleViewController
}
}
extension UITabBarController {
override open func topUIViewController() -> UIViewController? {
return self.selectedViewController ?? presentedViewController
}
}
现在,您可以使用它从您的应用程序中获取topUIViewController,而与您拥有的UIViewController堆栈无关,包括UINavigationController,UITabBarViewController。
let topVC = UIApplication.shared.keyWindow!.rootViewController!.topUIViewController()