我对Swift比较新
试图使用peek和pop previewActionItems"编辑"在编辑模式下打开SpeciesDetailViewController。有一个问题试图让segue呈现SpeciesDetailViewController并收到错误消息"Warning: Attempt to present SpeciesDetailViewController whose view is not in the window hierarchy"
。我实施了Jacob Davis' found here上的解决方案。
这修复了窗口层次结构错误,但是当调用SpeciesDetailViewController控制器时,导航控制器和tabBarController都不显示。
虽然我认为这是由于被调用为顶级viewController的SpeciesDetailViewController引起的,但我对如何修复它感到茫然。
你能帮我看一下导航控制器和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
}
答案 0 :(得分:0)
对于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()