Skip to content

Instantly share code, notes, and snippets.

@xinnyu
Forked from snikch/gist:3661188
Last active May 9, 2019 07:05
Show Gist options
  • Select an option

  • Save xinnyu/7eed9321220c3a82bd111413d81dbf14 to your computer and use it in GitHub Desktop.

Select an option

Save xinnyu/7eed9321220c3a82bd111413d81dbf14 to your computer and use it in GitHub Desktop.
Find the current top view controller for your iOS application
+ (UIViewController *)topViewController {
UIViewController *resultVC;
resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
while (resultVC.presentedViewController) {
resultVC = [self _topViewController:resultVC.presentedViewController];
}
return resultVC;
}
+ (UIViewController *)_topViewController:(UIViewController *)vc {
if ([vc isKindOfClass:[UINavigationController class]]) {
return [self _topViewController:[(UINavigationController *)vc topViewController]];
} else if ([vc isKindOfClass:[UITabBarController class]]) {
return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
} else {
return vc;
}
return nil;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment