我正在尝试检查特定的VC,如果应用程序在前台运行。我的根视图控制器类是SWRevealViewController
。之后,我有一个TabBarController
,在它下面有NavigationController
和ViewController
。
我的喜乐是
SWRevealViewController-> TabBar控制器->导航控制器-> MessageVC-> ChatVC
如果应用程序是在ChatVC上运行的,我想签入应用程序委托。我已经尝试过此代码,
let tabBar:UITabBarController = self.window?.rootViewController as! UITabBarController
let navInTab:UINavigationController = tabBar.viewControllers?[1] as! UINavigationController
let storyboard = UIStoryboard(name: "Dashboard", bundle: nil)
let destinationViewController = storyboard.instantiateViewController(withIdentifier: "ChatDetailViewController") as? ChatDetailViewController
if destinationViewController?.restorationIdentifier == "ChatDetailViewController"
{
print("Yes")
}
else
{
print("No")
}
但应用程式因这个错误而当机,
无法将类型'SWRevealViewController'(0x100dc4b20)的值强制转换为'UITabBarController'(0x211b289f0)。
我如何检查应用程序是否在ChatVC上?
分镜脚本截图:
最佳答案
我有一个扩展
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 {
let moreNavigationController = tab.moreNavigationController
if let top = moreNavigationController.topViewController, top.view.window != nil {
return topViewController(base: top)
} else if let selected = tab.selectedViewController {
return topViewController(base: selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(base: presented)
}
return base
}
}
用法:
if UIApplication.topViewController is YourViewController {
//做某事
}