Created
September 6, 2012 23:16
Find the current top view controller for your iOS application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (UIViewController *)topViewController{ | |
return [self topViewController:[UIApplication sharedApplication].keyWindow.rootViewController]; | |
} | |
- (UIViewController *)topViewController:(UIViewController *)rootViewController | |
{ | |
if (rootViewController.presentedViewController == nil) { | |
return rootViewController; | |
} | |
if ([rootViewController.presentedViewController isMemberOfClass:[UINavigationController class]]) { | |
UINavigationController *navigationController = (UINavigationController *)rootViewController.presentedViewController; | |
UIViewController *lastViewController = [[navigationController viewControllers] lastObject]; | |
return [self topViewController:lastViewController]; | |
} | |
UIViewController *presentedViewController = (UIViewController *)rootViewController.presentedViewController; | |
return [self topViewController:presentedViewController]; | |
} |
My ver to find topViewController with SSASideMenu
public extension UIApplication {
public class func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let SSASide = base as? SSASideMenu {
if let nav = SSASide.contentViewController as? UINavigationController{
return topViewController(nav.visibleViewController)
}
}
if let nav = base as? UINavigationController {
return topViewController(nav.visibleViewController)
}
if let tab = base as? UITabBarController {
let moreNavigationController = tab.moreNavigationController
if let top = moreNavigationController.topViewController, top.view.window != nil {
return topViewController(top)
} else if let selected = tab.selectedViewController {
return topViewController(selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(presented)
}
return base
}
I like mohammadshalhoob's version because it takes moreNavigationController into account. However, I found that moreNavigationController.topViewController.view.window != nil didn't work as intended when used in viewWillAppear, before the view is attached to the window. To test whether the sixth or more view controller is selected, I just used tab.selectedIndex > 4.
I'm curious where UIViewController's children has gone?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@wubingwell : i had the same problem, solved like this
Usage :