问题
当前的viewController不是
rootViewControllerfrom
UIApplication。因此,您应该找到当前可见的viewController,然后从那里显示它。
解
只需在上找到topViewController
UIApplication Stack,然后从那里显示您的控制器。
let newViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "viewController2")UIApplication.topViewController()?.present(newViewController, animated: true, completion: nil)
的扩展名可
UIApplication为您提供方便
extension UIApplication { class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { if let nav = base as? UINavigationController { return topViewController(base: nav.visibleViewController) } if let tab = base as? UITabBarController { if let selected = tab.selectedViewController { return topViewController(base: selected) } } if let presented = base?.presentedViewController { return topViewController(base: presented) } return base }}参考:Gist



