Skip to content

Instantly share code, notes, and snippets.

@snikch
Created September 6, 2012 23:16
Show Gist options
  • Save snikch/3661188 to your computer and use it in GitHub Desktop.
Save snikch/3661188 to your computer and use it in GitHub Desktop.
Find the current top view controller for your iOS application
- (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];
}
@kwallace-abvio
Copy link

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.

@18930369486
Copy link

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